{ "source": "doc/api/all.md", "desc": [ { "type": "html", "pre": false, "text": "\n" } ], "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.
\nWhere appropriate, property types, method arguments, and the arguments\nprovided to event handlers are detailed in a list underneath the topic\nheading.
\nEvery .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.
Every .html
and .json
file is generated based on the corresponding\n.md
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
.
If you find an error in this documentation, please submit an issue\nor see the contributing guide for directions on how to submit a patch.
\n", "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.
\nThe stability indices are as follows:
\nStability: 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
\nStability: 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
\nStability: 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
\nStability: 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
\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.
\nThis feature was added in Node.js v0.6.12. It is experimental.
\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.
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.
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": "Usage", "name": "Usage", "type": "misc", "desc": "node [options] [v8 options] [script.js | -e "script"] [arguments]
Please see the Command Line Options document for information about\ndifferent options and ways to run scripts with Node.js.
\nAn example of a web server written with Node.js which responds with\n'Hello World'
:
const http = require('http');\n\nconst hostname = '127.0.0.1';\nconst port = 3000;\n\nconst server = http.createServer((req, res) => {\n res.statusCode = 200;\n res.setHeader('Content-Type', 'text/plain');\n res.end('Hello World\\n');\n});\n\nserver.listen(port, hostname, () => {\n console.log(`Server running at http://${hostname}:${port}/`);\n});\n
\nTo run the server, put the code into a file called example.js
and execute\nit with Node.js:
$ node example.js\nServer running at http://127.0.0.1:3000/\n
\nAll 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 variety of CLI options. These options expose built-in\ndebugging, multiple ways to execute scripts, and other helpful runtime options.
\nTo view this documentation as a manual page in your terminal, run man node
.
node [options] [v8 options] [script.js | -e "script"] [--] [arguments]
node debug [script.js | -e "script" | <host>:<port>] …
node --v8-options
Execute without arguments to start the REPL.
\nFor more info about node debug
, please see the debugger documentation.
Print node's version.
\n", "type": "module", "displayName": "`-v`, `--version`" }, { "textRaw": "`-h`, `--help`", "name": "`-h`,_`--help`", "meta": { "added": [ "v0.1.3" ] }, "desc": "Print node command line options.\nThe output of this option is less detailed than this document.
\n", "type": "module", "displayName": "`-h`, `--help`" }, { "textRaw": "`-e`, `--eval \"script\"`", "name": "`-e`,_`--eval_\"script\"`", "meta": { "added": [ "v0.5.2" ] }, "desc": "Evaluate the following argument as JavaScript. The modules which are\npredefined in the REPL can also be used in script
.
Identical to -e
but prints the result.
Syntax check the script without executing.
\n", "type": "module", "displayName": "`-c`, `--check`" }, { "textRaw": "`-i`, `--interactive`", "name": "`-i`,_`--interactive`", "meta": { "added": [ "v0.7.7" ] }, "desc": "Opens the REPL even if stdin does not appear to be a terminal.
\n", "type": "module", "displayName": "`-i`, `--interactive`" }, { "textRaw": "`-r`, `--require module`", "name": "`-r`,_`--require_module`", "meta": { "added": [ "v1.6.0" ] }, "desc": "Preload the specified module at startup.
\nFollows require()
's module resolution\nrules. module
may be either a path to a file, or a node module name.
Silence deprecation warnings.
\n", "type": "module", "displayName": "`--no-deprecation`" }, { "textRaw": "`--trace-deprecation`", "name": "`--trace-deprecation`", "meta": { "added": [ "v0.8.0" ] }, "desc": "Print stack traces for deprecations.
\n", "type": "module", "displayName": "`--trace-deprecation`" }, { "textRaw": "`--throw-deprecation`", "name": "`--throw-deprecation`", "meta": { "added": [ "v0.11.14" ] }, "desc": "Throw errors for deprecations.
\n", "type": "module", "displayName": "`--throw-deprecation`" }, { "textRaw": "`--no-warnings`", "name": "`--no-warnings`", "meta": { "added": [ "v6.0.0" ] }, "desc": "Silence all process warnings (including deprecations).
\n", "type": "module", "displayName": "`--no-warnings`" }, { "textRaw": "`--trace-warnings`", "name": "`--trace-warnings`", "meta": { "added": [ "v6.0.0" ] }, "desc": "Print stack traces for process warnings (including deprecations).
\n", "type": "module", "displayName": "`--trace-warnings`" }, { "textRaw": "`--trace-sync-io`", "name": "`--trace-sync-io`", "meta": { "added": [ "v2.1.0" ] }, "desc": "Prints a stack trace whenever synchronous I/O is detected after the first turn\nof the event loop.
\n", "type": "module", "displayName": "`--trace-sync-io`" }, { "textRaw": "`--zero-fill-buffers`", "name": "`--zero-fill-buffers`", "meta": { "added": [ "v6.0.0" ] }, "desc": "Automatically zero-fills all newly allocated Buffer and SlowBuffer\ninstances.
\n", "type": "module", "displayName": "`--zero-fill-buffers`" }, { "textRaw": "`--preserve-symlinks`", "name": "`--preserve-symlinks`", "meta": { "added": [ "v6.3.0" ] }, "desc": "Instructs the module loader to preserve symbolic links when resolving and\ncaching modules.
\nBy default, when Node.js loads a module from a path that is symbolically linked\nto a different on-disk location, Node.js will dereference the link and use the\nactual on-disk "real path" of the module as both an identifier and as a root\npath to locate other dependency modules. In most cases, this default behavior\nis acceptable. However, when using symbolically linked peer dependencies, as\nillustrated in the example below, the default behavior causes an exception to\nbe thrown if moduleA
attempts to require moduleB
as a peer dependency:
{appDir}\n ├── app\n │ ├── index.js\n │ └── node_modules\n │ ├── moduleA -> {appDir}/moduleA\n │ └── moduleB\n │ ├── index.js\n │ └── package.json\n └── moduleA\n ├── index.js\n └── package.json\n
\nThe --preserve-symlinks
command line flag instructs Node.js to use the\nsymlink path for modules as opposed to the real path, allowing symbolically\nlinked peer dependencies to be found.
Note, however, that using --preserve-symlinks
can have other side effects.\nSpecifically, symbolically linked native modules can fail to load if those\nare linked from more than one location in the dependency tree (Node.js would\nsee those as two separate modules and would attempt to load the module multiple\ntimes, causing an exception to be thrown).
Track heap object allocations for heap snapshots.
\n", "type": "module", "displayName": "`--track-heap-objects`" }, { "textRaw": "`--prof-process`", "name": "`--prof-process`", "meta": { "added": [ "v5.2.0" ] }, "desc": "Process v8 profiler output generated using the v8 option --prof
.
Print v8 command line options.
\nNote: v8 options allow words to be separated by both dashes (-
) or underscores\n(_
).
For example, --stack-trace-limit
is equivalent to --stack_trace_limit
.
Specify an alternative default TLS cipher list. (Requires Node.js to be built\nwith crypto support. (Default))
\n", "type": "module", "displayName": "`--tls-cipher-list=list`" }, { "textRaw": "`--enable-fips`", "name": "`--enable-fips`", "meta": { "added": [ "v6.0.0" ] }, "desc": "Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with\n./configure --openssl-fips
)
Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)\n(Same requirements as --enable-fips
)
Load an OpenSSL configuration file on startup. Among other uses, this can be\nused to enable FIPS-compliant crypto if Node.js is built with\n./configure --openssl-fips
.
Use OpenSSL's default CA store or use bundled Mozilla CA store as supplied by\ncurrent NodeJS version. The default store is selectable at build-time.
\nUsing OpenSSL store allows for external modifications of the store. For most\nLinux and BSD distributions, this store is maintained by the distribution\nmaintainers and system administrators. OpenSSL CA store location is dependent on\nconfiguration of the OpenSSL library but this can be altered at runtime using\nenvironmental variables.
\nThe bundled CA store, as supplied by NodeJS, is a snapshot of Mozilla CA store\nthat is fixed at release time. It is identical on all supported platforms.
\nSee SSL_CERT_DIR
and SSL_CERT_FILE
.
Specify ICU data load path. (overrides NODE_ICU_DATA
)
Indicate the end of node options. Pass the rest of the arguments to the script.\nIf no script filename or eval/print script is supplied prior to this, then\nthe next argument will be used as a script filename.
\n", "type": "module", "displayName": "`--`" } ], "type": "misc", "displayName": "Options" }, { "textRaw": "Environment Variables", "name": "environment_variables", "modules": [ { "textRaw": "`NODE_DEBUG=module[,…]`", "name": "`node_debug=module[,…]`", "meta": { "added": [ "v0.1.32" ] }, "desc": "','
-separated list of core modules that should print debug information.
':'
-separated list of directories prefixed to the module search path.
Note: on Windows, this is a ';'
-separated list instead.
When set to 1
colors will not be used in the REPL.
Data path for ICU (Intl object) data. Will extend linked-in data when compiled\nwith small-icu support.
\n", "type": "module", "displayName": "`NODE_ICU_DATA=file`" }, { "textRaw": "`NODE_NO_WARNINGS=1`", "name": "`node_no_warnings=1`", "meta": { "added": [ "v7.5.0" ] }, "desc": "When set to 1
, process warnings are silenced.
When set to 1
, instructs the module loader to preserve symbolic links when\nresolving and caching modules.
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.
When set to 1
, writes to stdout
and stderr
will be non-blocking and\nasynchronous when outputting to a TTY on platforms which support async stdio.\nSetting this will void any guarantee that stdio will not be interleaved or\ndropped at program exit. Use of this mode is not recommended.
When set, the well known "root" CAs (like VeriSign) will be extended with the\nextra certificates in file
. The file should consist of one or more trusted\ncertificates in PEM format. A message will be emitted (once) with\nprocess.emitWarning()
if the file is missing or\nmisformatted, but any errors are otherwise ignored.
Note that neither the well known nor extra certificates are used when the ca
\noptions property is explicitly specified for a TLS or HTTPS client or server.
If --use-openssl-ca
is enabled, this overrides and sets OpenSSL's directory\ncontaining trusted certificates.
Note: Be aware that unless the child environment is explicitly set, this\nevironment variable will be inherited by any child processes, and if they use\nOpenSSL, it may cause them to trust the same CAs as node.
\n", "type": "module", "displayName": "`SSL_CERT_DIR=dir`" }, { "textRaw": "`SSL_CERT_FILE=file`", "name": "`ssl_cert_file=file`", "desc": "If --use-openssl-ca
is enabled, this overrides and sets OpenSSL's file\ncontaining trusted certificates.
Note: Be aware that unless the child environment is explicitly set, this\nevironment variable will be inherited by any child processes, and if they use\nOpenSSL, it may cause them to trust the same CAs as node.
\n\n\n", "type": "module", "displayName": "`SSL_CERT_FILE=file`" } ], "type": "misc", "displayName": "Environment Variables" } ] }, { "textRaw": "Debugger", "name": "Debugger", "stability": 2, "stabilityText": "Stable", "type": "misc", "desc": "Node.js includes an out-of-process debugging utility accessible via a\nTCP-based protocol and built-in debugging client. To use it, start Node.js\nwith the debug
argument followed by the path to the script to debug; a prompt\nwill be displayed indicating successful launch of the debugger:
$ 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
\nNode.js's debugger client is not a full-featured debugger, but simple step and\ninspection are possible.
\nInserting the statement debugger;
into the source code of a script will\nenable a breakpoint at that position in the code:
// myscript.js\nx = 5;\nsetTimeout(() => {\n debugger;\n console.log('world');\n}, 1000);\nconsole.log('hello');\n
\nOnce the debugger is run, a breakpoint will occur at line 4:
\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
\nThe repl
command allows code to be evaluated remotely. The next
command\nsteps to the next line. Type help
to see what other commands are available.
Pressing enter
without typing a command will repeat the previous debugger\ncommand.
It is possible to watch expression and variable values while debugging. On\nevery breakpoint, each expression from the watchers list will be evaluated\nin the current context and displayed immediately before the breakpoint's\nsource code listing.
\nTo begin watching an expression, type watch('my_expression')
. The command\nwatchers
will print the active watchers. To remove a watcher, type\nunwatch('my_expression')
.
cont
, c
- Continue executionnext
, n
- Step nextstep
, s
- Step inout
, o
- Step outpause
- Pause running code (like pause button in Developer Tools)setBreakpoint()
, sb()
- Set breakpoint on current linesetBreakpoint(line)
, sb(line)
- Set breakpoint on specific linesetBreakpoint('fn()')
, sb(...)
- Set breakpoint on a first statement in\nfunctions bodysetBreakpoint('script.js', 1)
, sb(...)
- Set breakpoint on first line of\nscript.jsclearBreakpoint('script.js', 1)
, cb(...)
- Clear breakpoint in script.js\non line 1It is also possible to set a breakpoint in a file (module) that\nis not loaded yet:
\n$ node 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
\n",
"type": "module",
"displayName": "Breakpoints"
},
{
"textRaw": "Execution control",
"name": "Execution control",
"desc": "run
- Run script (automatically runs on debugger's start)restart
- Restart scriptkill
- Kill scriptscripts
- List all loaded scriptsversion
- Display V8's versionAn 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
.
Once a process has been set in debug mode this way, it can be inspected\nusing the Node.js debugger by either connecting to the pid
of the running\nprocess or via URI reference to the listening debugger:
node debug -p <pid>
- Connects to the process via the pid
node debug <URI>
- Connects to the process via the URI such as\nlocalhost:5858NOTE: This is an experimental feature.
\nV8 Inspector integration allows attaching Chrome DevTools to Node.js\ninstances for debugging and profiling.
\nV8 Inspector can be enabled by passing the --inspect
flag when starting a\nNode.js application. It is also possible to supply a custom port with that flag,\ne.g. --inspect=9222
will accept DevTools connections on port 9222.
To break on the first line of the application code, provide the --debug-brk
\nflag in addition to --inspect
.
$ node --inspect index.js\nDebugger listening on port 9229.\nWarning: This is an experimental feature and could change at any time.\nTo start debugging, open the following URL in Chrome:\n chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node\n
\n\n\n"
}
]
},
{
"textRaw": "Errors",
"name": "Errors",
"type": "misc",
"desc": "Applications running in Node.js will generally experience four categories of\nerrors:
\neval()
fails.assert
module.All JavaScript and System errors raised by Node.js inherit from, or are\ninstances of, the standard JavaScript {Error} class and are guaranteed\nto provide at least the properties available on that class.
\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.
\nAll 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.
// 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
\nAny 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.
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.
Errors that occur within Asynchronous APIs may be reported in multiple ways:
\nMost asynchronous methods that accept a callback
function will accept an\nError
object passed as the first argument to that function. If that first\nargument is not null
and is an instance of Error
, then an error occurred\nthat should be handled.
const fs = require('fs');\nfs.readFile('a file that does not exist', (err, data) => {\n if (err) {\n console.error('There was an error reading the file!', err);\n return;\n }\n // Otherwise handle the data\n});\n
\nWhen an asynchronous method is called on an object that is an EventEmitter
,\nerrors can be routed to that object's 'error'
event.
const net = require('net');\nconst connection = net.connect('localhost');\n\n// Adding an 'error' event handler to a stream:\nconnection.on('error', (err) => {\n // If the connection is reset by the server, or if it can't\n // connect at all, or on any sort of error encountered by\n // the connection, the error will be sent here.\n console.error(err);\n});\n\nconnection.pipe(process.stdout);\n
\nA handful of typically asynchronous methods in the Node.js API may still\nuse the throw
mechanism to raise exceptions that must be handled using\ntry / catch
. There is no comprehensive list of such methods; please\nrefer to the documentation of each method to determine the appropriate\nerror handling mechanism required.
The use of the 'error'
event mechanism is most common for stream-based\nand event emitter-based APIs, which themselves represent a series of\nasynchronous operations over time (as opposed to a single operation that may\npass or fail).
For all EventEmitter
objects, if an 'error'
event handler is not\nprovided, the error will be thrown, causing the Node.js process to report an\nunhandled exception and crash unless either: The domain
module is used\nappropriately or a handler has been registered for the\nprocess.on('uncaughtException')
event.
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
\nErrors generated in this way cannot be intercepted using try / catch
as\nthey are thrown after the calling code has already exited.
Developers must refer to the documentation for each method to determine\nexactly how errors raised by those methods are propagated.
\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
.
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
\nThe 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:
// 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
\nThis 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.
A JavaScript exception is a value that is thrown as a result of an invalid\noperation or as the target of a throw
statement. While it is not required\nthat these values are instances of Error
or classes which inherit from\nError
, all exceptions thrown by Node.js or the JavaScript runtime will be\ninstances of Error.
Some exceptions are unrecoverable at the JavaScript layer. Such exceptions\nwill always cause the Node.js process to crash. Examples include assert()
\nchecks or abort()
calls in the C++ layer.
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.
\nSystem 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.
In Node.js, system errors are represented as augmented Error
objects with\nadded properties.
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
.
Returns a number corresponding to the negated error code, which may be\nreferenced in man 2 intro
. For example, an ENOENT
error has an errno
of\n-2
because the error code for ENOENT
is 2
.
Returns a string describing the syscall that failed.
\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.
\nEACCES
(Permission denied): An attempt was made to access a file in a way\nforbidden by its file access permissions.
EADDRINUSE
(Address already in use): An attempt to bind a server\n(net
, http
, or https
) to a local address failed due to\nanother server on the local system already occupying that address.
ECONNREFUSED
(Connection refused): No connection could be made because the\ntarget machine actively refused it. This usually results from trying to\nconnect to a service that is inactive on the foreign host.
ECONNRESET
(Connection reset by peer): A connection was forcibly closed by\na peer. This normally results from a loss of the connection on the remote\nsocket due to a timeout or reboot. Commonly encountered via the http
\nand net
modules.
EEXIST
(File exists): An existing file was the target of an operation that\nrequired that the target not exist.
EISDIR
(Is a directory): An operation expected a file, but the given\npathname was a directory.
EMFILE
(Too many open files in system): Maximum number of\nfile descriptors allowable on the system has been reached, and\nrequests for another descriptor cannot be fulfilled until at least one\nhas been closed. This is encountered when opening many files at once in\nparallel, especially on systems (in particular, OS X) where there is a low\nfile descriptor limit for processes. To remedy a low limit, run\nulimit -n 2048
in the same shell that will run the Node.js process.
ENOENT
(No such file or directory): Commonly raised by fs
operations\nto indicate that a component of the specified pathname does not exist -- no\nentity (file or directory) could be found by the given path.
ENOTDIR
(Not a directory): A component of the given pathname existed, but\nwas not a directory as expected. Commonly raised by fs.readdir
.
ENOTEMPTY
(Directory not empty): A directory with entries was the target\nof an operation that requires an empty directory -- usually fs.unlink
.
EPERM
(Operation not permitted): An attempt was made to perform an\noperation that requires elevated privileges.
EPIPE
(Broken pipe): A write on a pipe, socket, or FIFO for which there is\nno process to read the data. Commonly encountered at the net
and\nhttp
layers, indicative that the remote side of the stream being\nwritten to has been closed.
ETIMEDOUT
(Operation timed out): A connect or send request failed because\nthe connected party did not properly respond after a period of time. Usually\nencountered by http
or net
-- often a sign that a socket.end()
\nwas not properly called.
A generic JavaScript Error
object that does not denote any specific\ncircumstance of why the error occurred. Error
objects capture a "stack trace"\ndetailing the point in the code at which the Error
was instantiated, and may\nprovide a text description of the error.
All errors generated by Node.js, including all System and JavaScript errors,\nwill either be instances of, or inherit from, the Error
class.
Creates a .stack
property on targetObject
, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace()
was called.
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack // similar to `new Error().stack`\n
\nThe first line of the trace, instead of being prefixed with ErrorType:\nmessage
, will be the result of calling targetObject.toString()
.
The optional constructorOpt
argument accepts a function. If given, all frames\nabove constructorOpt
, including constructorOpt
, will be omitted from the\ngenerated stack trace.
The constructorOpt
argument is useful for hiding implementation\ndetails of error generation from an end user. For instance:
function MyError() {\n Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame and all frames above it.\nnew MyError().stack\n
\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)
).
The default value is 10
but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.
\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.
const err = new Error('The message');\nconsole.log(err.message);\n// Prints: The message\n
\n"
},
{
"textRaw": "error.stack",
"name": "stack",
"desc": "Returns a string describing the point in the code at which the Error
was\ninstantiated.
For example:
\nError: Things keep happening!\n at /home/gbusey/file.js:525:2\n at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n at increaseSynergy (/home/gbusey/actors.js:701:6)\n
\nThe first line is formatted as <error class name>: <error message>
, and\nis followed by a series of stack frames (each line beginning with "at ").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.
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:
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
\nThe location information will be one of:
\nnative
, if the frame represents a call internal to V8 (as in [].forEach
).plain-filename.js:line:column
, if the frame represents a call internal\n to Node.js./absolute/path/to/file.js:line:column
, if the frame represents a call in\na user program, or its dependencies.The string representing the stack trace is lazily generated when the\nerror.stack
property is accessed.
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.
System-level errors are generated as augmented Error
instances, which are\ndetailed here.
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.
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.
For example:
\nrequire('net').connect(-1);\n // throws RangeError, port should be > 0 && < 65536\n
\nNode.js will generate and throw RangeError
instances immediately as a form\nof argument validation.
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.
While client code may generate and propagate these errors, in practice, only V8\nwill do so.
\ndoesNotExist;\n // throws ReferenceError, doesNotExist is not a variable in this program.\n
\nReferenceError
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.
const assert = require('assert');\ntry {\n doesNotExist;\n} catch(err) {\n assert(err.arguments[0], 'doesNotExist');\n}\n
\nUnless an application is dynamically generating and running code,\nReferenceError
instances should always be considered a bug in the code\nor its dependencies.
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.
try {\n require('vm').runInThisContext('binary ! isNotOk');\n} catch(err) {\n // err will be a SyntaxError\n}\n
\nSyntaxError
instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.
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.
require('url').parse(() => { });\n // throws TypeError, since it expected a string\n
\nNode.js will generate and throw TypeError
instances immediately as a form\nof argument validation.
These objects are available in all modules. Some of these objects aren't\nactually in the global scope but in the module scope - this will be noted.
\nThe objects listed here are specific to Node.js. There are a number of\nbuilt-in objects that are part of the JavaScript language itself, which are\nalso globally accessible.
\n", "globals": [ { "textRaw": "Class: Buffer", "type": "global", "name": "Buffer", "meta": { "added": [ "v0.1.103" ] }, "desc": "Used to handle binary data. See the buffer section.
\n" }, { "textRaw": "clearImmediate(immediateObject)", "type": "global", "name": "clearImmediate", "meta": { "added": [ "v0.9.1" ] }, "desc": "clearImmediate
is described in the timers section.
clearInterval
is described in the timers section.
clearTimeout
is described in the timers section.
Used to print to stdout and stderr. See the console
section.
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.
The process object. See the process
object section.
setImmediate
is described in the timers section.
setInterval
is described in the timers section.
setTimeout
is described in the timers section.
The process
object is a global
that provides information about, and control\nover, the current Node.js process. As a global, it is always available to\nNode.js applications without using require()
.
The process
object is an instance of EventEmitter
.
The 'beforeExit'
event is emitted when Node.js empties its event loop and has\nno additional work to schedule. Normally, the Node.js process will exit when\nthere is no work scheduled, but a listener registered on the 'beforeExit'
\nevent can make asynchronous calls, and thereby cause the Node.js process to\ncontinue.
The listener callback function is invoked with the value of\nprocess.exitCode
passed as the only argument.
The 'beforeExit'
event is not emitted for conditions causing explicit\ntermination, such as calling process.exit()
or uncaught exceptions.
The 'beforeExit'
should not be used as an alternative to the 'exit'
event\nunless the intention is to schedule additional work.
If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'disconnect'
event will be emitted when\nthe IPC channel is closed.
The 'exit'
event is emitted when the Node.js process is about to exit as a\nresult of either:
process.exit()
method being called explicitly;There is no way to prevent the exiting of the event loop at this point, and once\nall 'exit'
listeners have finished running the Node.js process will terminate.
The listener callback function is invoked with the exit code specified either\nby the process.exitCode
property, or the exitCode
argument passed to the\nprocess.exit()
method, as the only argument.
For example:
\nprocess.on('exit', (code) => {\n console.log(`About to exit with code: ${code}`);\n});\n
\nListener functions must only perform synchronous operations. The Node.js\nprocess will exit immediately after calling the 'exit'
event listeners\ncausing any additional work still queued in the event loop to be abandoned.\nIn the following example, for instance, the timeout will never occur:
process.on('exit', (code) => {\n setTimeout(() => {\n console.log('This will not run');\n }, 0);\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'message'",
"type": "event",
"name": "message",
"meta": {
"added": [
"v0.5.10"
]
},
"desc": "If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'message'
event is emitted whenever a\nmessage sent by a parent process using childprocess.send()
is received by\nthe child process.
The listener callback is invoked with the following arguments:
\nmessage
{Object} a parsed JSON object or primitive valuesendHandle
{Handle object} a net.Socket
or net.Server
object, or\nundefined.The 'rejectionHandled'
event is emitted whenever a Promise
has been rejected\nand an error handler was attached to it (using promise.catch()
, for\nexample) later than one turn of the Node.js event loop.
The listener callback is invoked with a reference to the rejected Promise
as\nthe only argument.
The Promise
object would have previously been emitted in an\n'unhandledRejection'
event, but during the course of processing gained a\nrejection handler.
There is no notion of a top level for a Promise
chain at which rejections can\nalways be handled. Being inherently asynchronous in nature, a Promise
\nrejection can be handled at a future point in time — possibly much later than\nthe event loop turn it takes for the 'unhandledRejection'
event to be emitted.
Another way of stating this is that, unlike in synchronous code where there is\nan ever-growing list of unhandled exceptions, with Promises there can be a\ngrowing-and-shrinking list of unhandled rejections.
\nIn synchronous code, the 'uncaughtException'
event is emitted when the list of\nunhandled exceptions grows.
In asynchronous code, the 'unhandledRejection'
event is emitted when the list\nof unhandled rejections grows, and the 'rejectionHandled'
event is emitted\nwhen the list of unhandled rejections shrinks.
For example:
\nconst unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, p) => {\n unhandledRejections.set(p, reason);\n});\nprocess.on('rejectionHandled', (p) => {\n unhandledRejections.delete(p);\n});\n
\nIn this example, the unhandledRejections
Map
will grow and shrink over time,\nreflecting rejections that start unhandled and then become handled. It is\npossible to record such errors in an error log, either periodically (which is\nlikely best for long-running application) or upon process exit (which is likely\nmost convenient for scripts).
The 'uncaughtException'
event is emitted when an uncaught JavaScript\nexception bubbles all the way back to the event loop. By default, Node.js\nhandles such exceptions by printing the stack trace to stderr
and exiting.\nAdding a handler for the 'uncaughtException'
event overrides this default\nbehavior.
The listener function is called with the Error
object passed as the only\nargument.
For example:
\nprocess.on('uncaughtException', (err) => {\n fs.writeSync(1, `Caught exception: ${err}`);\n});\n\nsetTimeout(() => {\n console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');\n
\n",
"modules": [
{
"textRaw": "Warning: Using `'uncaughtException'` correctly",
"name": "warning:_using_`'uncaughtexception'`_correctly",
"desc": "Note that 'uncaughtException'
is a crude mechanism for exception handling\nintended to be used only as a last resort. The event should not be used as\nan equivalent to On Error Resume Next
. Unhandled exceptions inherently mean\nthat an application is in an undefined state. Attempting to resume application\ncode without properly recovering from the exception can cause additional\nunforeseen and unpredictable issues.
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.
\nAttempting 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.
\nThe 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'
.
To restart a crashed application in a more reliable way, whether uncaughtException
\nis emitted or not, an external monitor should be employed in a separate process\nto detect application failures and recover or restart as needed.
The 'unhandledRejection
' event is emitted whenever a Promise
is rejected and\nno error handler is attached to the promise within a turn of the event loop.\nWhen programming with Promises, exceptions are encapsulated as "rejected\npromises". Rejections can be caught and handled using promise.catch()
and\nare propagated through a Promise
chain. The 'unhandledRejection'
event is\nuseful for detecting and keeping track of promises that were rejected whose\nrejections have not yet been handled.
The listener function is called with the following arguments:
\nreason
{Error|any} The object with which the promise was rejected\n(typically an Error
object).p
the Promise
that was rejected.For example:
\nprocess.on('unhandledRejection', (reason, p) => {\n console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);\n // application specific logging, throwing an error, or other logic here\n});\n\nsomePromise.then((res) => {\n return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)\n}); // no `.catch` or `.then`\n
\nThe following will also trigger the 'unhandledRejection'
event to be\nemitted:
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
\nIn this example case, it is possible to track the rejection as a developer error\nas would typically be the case for other 'unhandledRejection'
events. To\naddress such failures, a non-operational\n.catch(() => { })
handler may be attached to\nresource.loaded
, which would prevent the 'unhandledRejection'
event from\nbeing emitted. Alternatively, the 'rejectionHandled'
event may be used.
The 'warning'
event is emitted whenever Node.js emits a process warning.
A process warning is similar to an error in that it describes exceptional\nconditions that are being brought to the user's attention. However, warnings\nare not part of the normal Node.js and JavaScript error handling flow.\nNode.js can emit warnings whenever it detects bad coding practices that could\nlead to sub-optimal application performance, bugs or security vulnerabilities.
\nThe listener function is called with a single warning
argument whose value is\nan Error
object. There are three key properties that describe the warning:
name
{String} The name of the warning (currently Warning
by default).message
{String} A system-provided description of the warning.stack
{String} A stack trace to the location in the code where the warning\nwas issued.process.on('warning', (warning) => {\n console.warn(warning.name); // Print the warning name\n console.warn(warning.message); // Print the warning message\n console.warn(warning.stack); // Print the stack trace\n});\n
\nBy default, Node.js will print process warnings to stderr
. The --no-warnings
\ncommand-line option can be used to suppress the default console output but the\n'warning'
event will still be emitted by the process
object.
The following example illustrates the warning that is printed to stderr
when\ntoo many listeners have been added to an event
$ node\n> event.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> (node:38638) Warning: Possible EventEmitter memory leak detected. 2 foo\n... listeners added. Use emitter.setMaxListeners() to increase limit\n
\nIn contrast, the following example turns off the default warning output and\nadds a custom handler to the 'warning'
event:
$ node --no-warnings\n> var p = process.on('warning', (warning) => console.warn('Do not do that!'));\n> event.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> Do not do that!\n
\nThe --trace-warnings
command-line option can be used to have the default\nconsole output for warnings include the full stack trace of the warning.
Launching Node.js using the --throw-deprecation
command line flag will\ncause custom deprecation warnings to be thrown as exceptions.
Using the --trace-deprecation
command line flag will cause the custom\ndeprecation to be printed to stderr
along with the stack trace.
Using the --no-deprecation
command line flag will suppress all reporting\nof the custom deprecation.
The *-deprecation
command line flags only affect warnings that use the name\nDeprecationWarning
.
See the process.emitWarning()
method for issuing\ncustom or application-specific warnings.
Signal events will be emitted when the Node.js process receives a signal. Please\nrefer to signal(7) for a listing of standard POSIX signal names such as\nSIGINT
, SIGHUP
, etc.
The name of each event will be the uppercase common name for the signal (e.g.\n'SIGINT'
for SIGINT
signals).
For example:
\n// Begin reading from stdin so the process does not exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n console.log('Received SIGINT. Press Control-D to exit.');\n});\n
\nNote: An easy way to send the SIGINT
signal is with <Ctrl>-C
in most\nterminal programs.
It is important to take note of the following:
\nSIGUSR1
is reserved by Node.js to start the debugger. It's possible to\ninstall a listener but doing so will not stop the debugger from starting.SIGTERM
and SIGINT
have default handlers on non-Windows platforms that\nresets the terminal mode before exiting with code 128 + signal number
. If\none of these signals has a listener installed, its default behavior will be\nremoved (Node.js will no longer exit).SIGPIPE
is ignored by default. It can have a listener installed.SIGHUP
is generated on Windows when the console window is closed, and on\nother platforms under various similar conditions, see signal(7). It can have a\nlistener installed, however Node.js will be unconditionally terminated by\nWindows about 10 seconds later. On non-Windows platforms, the default\nbehavior of SIGHUP
is to terminate Node.js, but once a listener has been\ninstalled its default behavior will be removed.SIGTERM
is not supported on Windows, it can be listened on.SIGINT
from the terminal is supported on all platforms, and can usually be\ngenerated with CTRL+C
(though this may be configurable). It is not generated\nwhen terminal raw mode is enabled.SIGBREAK
is delivered on Windows when <Ctrl>+<Break>
is pressed, on\nnon-Windows platforms it can be listened on, but there is no way to send or\ngenerate it.SIGWINCH
is delivered when the console has been resized. On Windows, this\nwill only happen on write to the console when the cursor is being moved, or\nwhen a readable tty is used in raw mode.SIGKILL
cannot have a listener installed, it will unconditionally terminate\nNode.js on all platforms.SIGSTOP
cannot have a listener installed.SIGBUS
, SIGFPE
, SIGSEGV
and SIGILL
, when not raised artificially\n using kill(2), inherently leave the process in a state from which it is not\n safe to attempt to call JS listeners. Doing so might lead to the process\n hanging in an endless loop, since listeners attached using process.on()
are\n called asynchronously and therefore unable to correct the underlying problem.Note: Windows does not support sending signals, but Node.js offers some\nemulation with process.kill()
, and ChildProcess.kill()
. Sending\nsignal 0
can be used to test for the existence of a process. Sending SIGINT
,\nSIGTERM
, and SIGKILL
cause the unconditional termination of the target\nprocess.
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:
1
Uncaught Fatal Exception - There was an uncaught exception,\nand it was not handled by a domain or an 'uncaughtException'
event\nhandler.2
- Unused (reserved by Bash for builtin misuse)3
Internal JavaScript Parse Error - The JavaScript source code\ninternal in Node.js's bootstrapping process caused a parse error. This\nis extremely rare, and generally can only happen during development\nof Node.js itself.4
Internal JavaScript Evaluation Failure - The JavaScript\nsource code internal in Node.js's bootstrapping process failed to\nreturn a function value when evaluated. This is extremely rare, and\ngenerally can only happen during development of Node.js itself.5
Fatal Error - There was a fatal unrecoverable error in V8.\nTypically a message will be printed to stderr with the prefix FATAL\nERROR
.6
Non-function Internal Exception Handler - There was an\nuncaught exception, but the internal fatal exception handler\nfunction was somehow set to a non-function, and could not be called.7
Internal Exception Handler Run-Time Failure - There was an\nuncaught exception, and the internal fatal exception handler\nfunction itself threw an error while attempting to handle it. This\ncan happen, for example, if a 'uncaughtException'
or\ndomain.on('error')
handler throws an error.8
- Unused. In previous versions of Node.js, exit code 8 sometimes\nindicated an uncaught exception.9
- Invalid Argument - Either an unknown option was specified,\nor an option requiring a value was provided without a value.10
Internal JavaScript Run-Time Failure - The JavaScript\nsource code internal in Node.js's bootstrapping process threw an error\nwhen the bootstrapping function was called. This is extremely rare,\nand generally can only happen during development of Node.js itself.12
Invalid Debug Argument - The --debug
, --inspect
and/or\n--debug-brk
options were set, but the port number chosen was invalid\nor unavailable.>128
Signal Exits - If Node.js receives a fatal signal such as\nSIGKILL
or SIGHUP
, then its exit code will be 128
plus the\nvalue of the signal code. This is a standard Unix practice, since\nexit codes are defined to be 7-bit integers, and signal exits set\nthe high-order bit, and then contain the value of the signal code.The process.abort()
method causes the Node.js process to exit immediately and\ngenerate a core file.
The process.chdir()
method changes the current working directory of the\nNode.js process or throws an exception if doing so fails (for instance, if\nthe specified directory
does not exist).
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
\n"
},
{
"textRaw": "process.cpuUsage([previousValue])",
"type": "method",
"name": "cpuUsage",
"meta": {
"added": [
"v6.1.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Object} ",
"options": [
{
"textRaw": "`user` {Integer} ",
"name": "user",
"type": "Integer"
},
{
"textRaw": "`system` {Integer} ",
"name": "system",
"type": "Integer"
}
],
"name": "return",
"type": "Object"
},
"params": [
{
"textRaw": "`previousValue` {Object} A previous return value from calling `process.cpuUsage()` ",
"name": "previousValue",
"type": "Object",
"desc": "A previous return value from calling `process.cpuUsage()`",
"optional": true
}
]
},
{
"params": [
{
"name": "previousValue",
"optional": true
}
]
}
],
"desc": "The process.cpuUsage()
method returns the user and system CPU time usage of\nthe current process, in an object with properties user
and system
, whose\nvalues are microsecond values (millionth of a second). These values measure time\nspent in user and system code respectively, and may end up being greater than\nactual elapsed time if multiple CPU cores are performing work for this process.
The result of a previous call to process.cpuUsage()
can be passed as the\nargument to the function, to get a diff reading.
const startUsage = process.cpuUsage();\n// { user: 38579, system: 6986 }\n\n// spin the CPU for 500 milliseconds\nconst now = Date.now();\nwhile (Date.now() - now < 500);\n\nconsole.log(process.cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
\n"
},
{
"textRaw": "process.cwd()",
"type": "method",
"name": "cwd",
"meta": {
"added": [
"v0.1.8"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {String} ",
"name": "return",
"type": "String"
},
"params": []
},
{
"params": []
}
],
"desc": "The process.cwd()
method returns the current working directory of the Node.js\nprocess.
console.log(`Current directory: ${process.cwd()}`);\n
\n"
},
{
"textRaw": "process.disconnect()",
"type": "method",
"name": "disconnect",
"meta": {
"added": [
"v0.7.2"
]
},
"desc": "If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.disconnect()
method will close the\nIPC channel to the parent process, allowing the child process to exit gracefully\nonce there are no other connections keeping it alive.
The effect of calling process.disconnect()
is that same as calling the parent\nprocess's ChildProcess.disconnect()
.
If the Node.js process was not spawned with an IPC channel,\nprocess.disconnect()
will be undefined
.
The process.emitWarning()
method can be used to emit custom or application\nspecific process warnings. These can be listened for by adding a handler to the\nprocess.on('warning')
event.
// Emit a warning using a string...\nprocess.emitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
\n// Emit a warning using a string and a name...\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) CustomWarning: Something Happened!\n
\nIn each of the previous examples, an Error
object is generated internally by\nprocess.emitWarning()
and passed through to the\nprocess.on('warning')
event.
process.on('warning', (warning) => {\n console.warn(warning.name);\n console.warn(warning.message);\n console.warn(warning.stack);\n});\n
\nIf warning
is passed as an Error
object, it will be passed through to the\nprocess.on('warning')
event handler unmodified (and the optional name
\nand ctor
arguments will be ignored):
// Emit a warning using an Error object...\nconst myWarning = new Error('Warning! Something happened!');\nmyWarning.name = 'CustomWarning';\n\nprocess.emitWarning(myWarning);\n// Emits: (node:56338) CustomWarning: Warning! Something Happened!\n
\nA TypeError
is thrown if warning
is anything other than a string or Error
\nobject.
Note that while process warnings use Error
objects, the process warning\nmechanism is not a replacement for normal error handling mechanisms.
The following additional handling is implemented if the warning name
is\nDeprecationWarning
:
--throw-deprecation
command-line flag is used, the deprecation\nwarning is thrown as an exception rather than being emitted as an event.--no-deprecation
command-line flag is used, the deprecation\nwarning is suppressed.--trace-deprecation
command-line flag is used, the deprecation\nwarning is printed to stderr
along with the full stack trace.As a best practice, warnings should be emitted only once per process. To do\nso, it is recommended to place the emitWarning()
behind a simple boolean\nflag as illustrated in the example below:
function emitMyWarning() {\n if (!emitMyWarning.warned) {\n emitMyWarning.warned = true;\n process.emitWarning('Only warn once!');\n }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
\n",
"type": "module",
"displayName": "Avoiding duplicate warnings"
}
]
},
{
"textRaw": "process.exit([code])",
"type": "method",
"name": "exit",
"meta": {
"added": [
"v0.1.13"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`code` {Integer} The exit code. Defaults to `0`. ",
"name": "code",
"type": "Integer",
"desc": "The exit code. Defaults to `0`.",
"optional": true
}
]
},
{
"params": [
{
"name": "code",
"optional": true
}
]
}
],
"desc": "The process.exit()
method instructs Node.js to terminate the process as\nquickly as possible with the specified exit code
. If the code
is omitted,\nexit uses either the 'success' code 0
or the value of process.exitCode
if\nspecified.
To exit with a 'failure' code:
\nprocess.exit(1);\n
\nThe shell that executed Node.js should see the exit code as 1
.
It is important to note that calling process.exit()
will force the process to\nexit as quickly as possible even if there are still asynchronous operations\npending that have not yet completed fully, including I/O operations to\nprocess.stdout
and process.stderr
.
In most situations, it is not actually necessary to call process.exit()
\nexplicitly. The Node.js process will exit on its own if there is no additional\nwork pending in the event loop. The process.exitCode
property can be set to\ntell the process which exit code to use when the process exits gracefully.
For instance, the following example illustrates a misuse of the\nprocess.exit()
method that could lead to data printed to stdout being\ntruncated and lost:
// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n printUsageToStdout();\n process.exit(1);\n}\n
\nThe reason this is problematic is because writes to process.stdout
in Node.js\nare sometimes non-blocking and may occur over multiple ticks of the Node.js\nevent loop. Calling process.exit()
, however, forces the process to exit\nbefore those additional writes to stdout
can be performed.
Rather than calling process.exit()
directly, the code should set the\nprocess.exitCode
and allow the process to exit naturally by avoiding\nscheduling any additional work for the event loop:
// How to properly set the exit code while letting\n// the process exit gracefully.\nif (someConditionNotMet()) {\n printUsageToStdout();\n process.exitCode = 1;\n}\n
\nIf it is necessary to terminate the Node.js process due to an error condition,\nthrowing an uncaught error and allowing the process to terminate accordingly\nis safer than calling process.exit()
.
The process.getegid()
method returns the numerical effective group identity\nof the Node.js process. (See getegid(2).)
if (process.getegid) {\n console.log(`Current gid: ${process.getegid()}`);\n}\n
\nNote: This function is only available on POSIX platforms (i.e. not Windows\nor Android)
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.geteuid()", "type": "method", "name": "geteuid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "The process.geteuid()
method returns the numerical effective user identity of\nthe process. (See geteuid(2).)
if (process.geteuid) {\n console.log(`Current uid: ${process.geteuid()}`);\n}\n
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "The process.getgid()
method returns the numerical group identity of the\nprocess. (See getgid(2).)
if (process.getgid) {\n console.log(`Current gid: ${process.getgid()}`);\n}\n
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Array} ", "name": "return", "type": "Array" }, "params": [] }, { "params": [] } ], "desc": "The process.getgroups()
method returns an array with the supplementary group\nIDs. POSIX leaves it unspecified if the effective group ID is included but\nNode.js ensures it always is.
Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "meta": { "added": [ "v0.1.28" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Integer} ", "name": "return", "type": "Integer" }, "params": [] }, { "params": [] } ], "desc": "The process.getuid()
method returns the numeric user identity of the process.\n(See getuid(2).)
if (process.getuid) {\n console.log(`Current uid: ${process.getuid()}`);\n}\n
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.hrtime([time])", "type": "method", "name": "hrtime", "meta": { "added": [ "v0.7.6" ] }, "desc": "The process.hrtime()
method returns the current high-resolution real time in a\n[seconds, nanoseconds]
tuple Array. time
is an optional parameter that must\nbe the result of a previous process.hrtime()
call (and therefore, a real time\nin a [seconds, nanoseconds]
tuple Array containing a previous time) to diff\nwith the current time. These times are relative to an arbitrary time in the\npast, and not related to the time of day and therefore not subject to clock\ndrift. The primary use is for measuring performance between intervals.
Passing in the result of a previous call to process.hrtime()
is useful for\ncalculating an amount of time passed between calls:
var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n var diff = process.hrtime(time);\n // [ 1, 552 ]\n\n console.log(`Benchmark took ${diff[0] * 1e9 + diff[1]} nanoseconds`);\n // benchmark took 1000000527 nanoseconds\n}, 1000);\n
\nConstructing an array by some method other than calling process.hrtime()
and\npassing the result to process.hrtime() will result in undefined behavior.
The process.initgroups()
method reads the /etc/group
file and initializes\nthe group access list, using all groups of which the user is a member. This is\na privileged operation that requires that the Node.js process either have root
\naccess or the CAP_SETGID
capability.
Note that care must be taken when dropping privileges. Example:
\nconsole.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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.kill(pid[, signal])", "type": "method", "name": "kill", "meta": { "added": [ "v0.0.6" ] }, "signatures": [ { "params": [ { "textRaw": "`pid` {number} A process ID ", "name": "pid", "type": "number", "desc": "A process ID" }, { "textRaw": "`signal` {String|number} The signal to send, either as a string or number. Defaults to `'SIGTERM'`. ", "name": "signal", "type": "String|number", "desc": "The signal to send, either as a string or number. Defaults to `'SIGTERM'`.", "optional": true } ] }, { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ], "desc": "The process.kill()
method sends the signal
to the process identified by\npid
.
Signal names are strings such as 'SIGINT'
or 'SIGHUP'
. See Signal Events\nand kill(2) for more information.
This method will throw an error if the target pid
does not exist. As a special\ncase, a signal of 0
can be used to test for the existence of a process.\nWindows platforms will throw an error if the pid
is used to kill a process\ngroup.
Note:Even though the name of this function is process.kill()
, it is really\njust a signal sender, like the kill
system call. The signal sent may do\nsomething other than kill the target process.
For example:
\nprocess.on('SIGHUP', () => {\n console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(() => {\n console.log('Exiting.');\n process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');\n
\nNote: When SIGUSR1
is received by a Node.js process, Node.js will start the\ndebugger, see Signal Events.
The process.memoryUsage()
method returns an object describing the memory usage\nof the Node.js process measured in bytes.
For example, the code:
\nconsole.log(process.memoryUsage());\n
\nWill generate:
\n{\n rss: 4935680,\n heapTotal: 1826816,\n heapUsed: 650472,\n external: 49879\n}\n
\nheapTotal
and heapUsed
refer to V8's memory usage.\nexternal
refers to the memory usage of C++ objects bound to JavaScript\nobjects managed by V8.
The process.nextTick()
method adds the callback
to the "next tick queue".\nOnce the current turn of the event loop turn runs to completion, all callbacks\ncurrently in the next tick queue will be called.
This is not a simple alias to setTimeout(fn, 0)
. It is much more\nefficient. It runs before any additional I/O events (including\ntimers) fire in subsequent ticks of the event loop.
console.log('start');\nprocess.nextTick(() => {\n console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback\n
\nThis is important when developing APIs in order to give users the opportunity\nto assign event handlers after an object has been constructed but before any\nI/O has occurred:
\nfunction 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
\nIt is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:
\n// WARNING! DO NOT USE! BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n if (arg) {\n cb();\n return;\n }\n\n fs.stat('file', cb);\n}\n
\nThis API is hazardous because in the following case:
\nmaybeSync(true, () => {\n foo();\n});\nbar();\n
\nIt is not clear whether foo()
or bar()
will be called first.
The following approach is much better:
\nfunction definitelyAsync(arg, cb) {\n if (arg) {\n process.nextTick(cb);\n return;\n }\n\n fs.stat('file', cb);\n}\n
\nNote: the next tick queue is completely drained on each pass of the\nevent loop before additional I/O is processed. As a result,\nrecursively setting nextTick callbacks will block any I/O from\nhappening, just like a while(true);
loop.
If Node.js is spawned with an IPC channel, the process.send()
method can be\nused to send messages to the parent process. Messages will be received as a\n'message'
event on the parent's ChildProcess
object.
If Node.js was not spawned with an IPC channel, process.send()
will be\nundefined
.
Note: This function uses JSON.stringify()
internally to serialize the\nmessage
.*
The process.setegid()
method sets the effective group identity of the process.\n(See setegid(2).) The id
can be passed as either a numeric ID or a group\nname string. If a group name is specified, this method blocks while resolving\nthe associated a numeric ID.
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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.seteuid(id)", "type": "method", "name": "seteuid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {String|number} A user name or ID ", "name": "id", "type": "String|number", "desc": "A user name or ID" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "The process.seteuid()
method sets the effective user identity of the process.\n(See seteuid(2).) The id
can be passed as either a numeric ID or a username\nstring. If a username is specified, the method blocks while resolving the\nassociated numeric ID.
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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {String|number} The group name or ID ", "name": "id", "type": "String|number", "desc": "The group name or ID" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "The process.setgid()
method sets the group identity of the process. (See\nsetgid(2).) The id
can be passed as either a numeric ID or a group name\nstring. If a group name is specified, this method blocks while resolving the\nassociated numeric ID.
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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "params": [ { "textRaw": "`groups` {Array} ", "name": "groups", "type": "Array" } ] }, { "params": [ { "name": "groups" } ] } ], "desc": "The process.setgroups()
method sets the supplementary group IDs for the\nNode.js process. This is a privileged operation that requires the Node.js process\nto have root
or the CAP_SETGID
capability.
The groups
array can contain numeric group IDs, group names or both.
Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "meta": { "added": [ "v0.1.28" ] }, "desc": "The process.setuid(id)
method sets the user identity of the process. (See\nsetuid(2).) The id
can be passed as either a numeric ID or a username string.\nIf a username is specified, the method blocks while resolving the associated\nnumeric ID.
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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "meta": { "added": [ "v0.1.19" ] }, "signatures": [ { "params": [ { "textRaw": "`mask` {number} ", "name": "mask", "type": "number", "optional": true } ] }, { "params": [ { "name": "mask", "optional": true } ] } ], "desc": "The process.umask()
method sets or returns the Node.js process's file mode\ncreation mask. Child processes inherit the mask from the parent process. The old\nmask is return if the mask
argument is given, otherwise returns the current\nmask.
const newmask = 0o022;\nconst oldmask = process.umask(newmask);\nconsole.log(\n `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
\n"
},
{
"textRaw": "process.uptime()",
"type": "method",
"name": "uptime",
"meta": {
"added": [
"v0.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Number} ",
"name": "return",
"type": "Number"
},
"params": []
},
{
"params": []
}
],
"desc": "The process.uptime()
method returns the number of seconds the current Node.js\nprocess has been running.
The process.arch
property returns a String identifying the processor\narchitecture that the Node.js process is currently running on. For instance\n'arm'
, 'ia32'
, or 'x64'
.
console.log(`This processor architecture is ${process.arch}`);\n
\n"
},
{
"textRaw": "`argv` {Array} ",
"type": "Array",
"name": "argv",
"meta": {
"added": [
"v0.1.27"
]
},
"desc": "The process.argv
property returns an array containing the command line\narguments passed when the Node.js process was launched. The first element will\nbe process.execPath
. See process.argv0
if access to the original value of\nargv[0]
is needed. The second element will be the path to the JavaScript\nfile being executed. The remaining elements will be any additional command line\narguments.
For example, assuming the following script for process-args.js
:
// print process.argv\nprocess.argv.forEach((val, index) => {\n console.log(`${index}: ${val}`);\n});\n
\nLaunching the Node.js process as:
\n$ node process-2.js one two=three four\n
\nWould generate the output:
\n0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four\n
\n"
},
{
"textRaw": "`argv0` {String} ",
"type": "String",
"name": "argv0",
"meta": {
"added": [
"6.4.0"
]
},
"desc": "The process.argv0
property stores a read-only copy of the original value of\nargv[0]
passed when Node.js starts.
$ bash -c 'exec -a customArgv0 ./node'\n> process.argv[0]\n'/Volumes/code/external/node/out/Release/node'\n> process.argv0\n'customArgv0'\n
\n"
},
{
"textRaw": "process.channel",
"name": "channel",
"meta": {
"added": [
"v7.1.0"
]
},
"desc": "If the Node.js process was spawned with an IPC channel (see the\nChild Process documentation), the process.channel
\nproperty is a reference to the IPC channel. If no IPC channel exists, this\nproperty is undefined
.
The process.config
property returns an Object containing the JavaScript\nrepresentation of the configure options used to compile the current Node.js\nexecutable. This is the same as the config.gypi
file that was produced when\nrunning the ./configure
script.
An example of the possible output looks like:
\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
\nNote: The process.config
property is not read-only and there are\nexisting modules in the ecosystem that are known to extend, modify, or entirely\nreplace the value of process.config
.
If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.connected
property will return\ntrue
so long as the IPC channel is connected and will return false
after\nprocess.disconnect()
is called.
Once process.connected
is false
, it is no longer possible to send messages\nover the IPC channel using process.send()
.
The process.env
property returns an object containing the user environment.\nSee environ(7).
An example of this object looks like:
\n{\n TERM: 'xterm-256color',\n SHELL: '/usr/local/bin/bash',\n USER: 'maciej',\n PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',\n PWD: '/Users/maciej',\n EDITOR: 'vim',\n SHLVL: '1',\n HOME: '/Users/maciej',\n LOGNAME: 'maciej',\n _: '/usr/local/bin/node'\n}\n
\nIt is possible to modify this object, but such modifications will not be\nreflected outside the Node.js process. In other words, the following example\nwould not work:
\n$ node -e 'process.env.foo = "bar"' && echo $foo\n
\nWhile the following will:
\nprocess.env.foo = 'bar';\nconsole.log(process.env.foo);\n
\nAssigning a property on process.env
will implicitly convert the value\nto a string.
Example:
\nprocess.env.test = null;\nconsole.log(process.env.test);\n// => 'null'\nprocess.env.test = undefined;\nconsole.log(process.env.test);\n// => 'undefined'\n
\nUse delete
to delete a property from process.env
.
Example:
\nprocess.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined\n
\nOn Windows operating systems, environment variables are case-insensitive.
\nExample:
\nprocess.env.TEST = 1;\nconsole.log(process.env.test);\n// => 1\n
\n"
},
{
"textRaw": "`execArgv` {Object} ",
"type": "Object",
"name": "execArgv",
"meta": {
"added": [
"v0.7.7"
]
},
"desc": "The process.execArgv
property returns the set of Node.js-specific command-line\noptions passed when the Node.js process was launched. These options do not\nappear in the array returned by the process.argv
property, and do not\ninclude the Node.js executable, the name of the script, or any options following\nthe script name. These options are useful in order to spawn child processes with\nthe same execution environment as the parent.
For example:
\n$ node --harmony script.js --version\n
\nResults in process.execArgv
:
['--harmony']\n
\nAnd process.argv
:
['/usr/local/bin/node', 'script.js', '--version']\n
\n"
},
{
"textRaw": "`execPath` {String} ",
"type": "String",
"name": "execPath",
"meta": {
"added": [
"v0.1.100"
]
},
"desc": "The process.execPath
property returns the absolute pathname of the executable\nthat started the Node.js process.
For example:
\n'/usr/local/bin/node'\n
\n"
},
{
"textRaw": "`exitCode` {Integer} ",
"type": "Integer",
"name": "exitCode",
"meta": {
"added": [
"v0.11.8"
]
},
"desc": "A number which will be the process exit code, when the process either\nexits gracefully, or is exited via process.exit()
without specifying\na code.
Specifying a code to process.exit(code)
will override any\nprevious setting of process.exitCode
.
The process.mainModule
property provides an alternative way of retrieving\nrequire.main
. The difference is that if the main module changes at\nruntime, require.main
may still refer to the original main module in\nmodules that were required before the change occurred. Generally, it's\nsafe to assume that the two refer to the same module.
As with require.main
, process.mainModule
will be undefined
if there\nis no entry script.
The process.pid
property returns the PID of the process.
console.log(`This process is pid ${process.pid}`);\n
\n"
},
{
"textRaw": "`platform` {String} ",
"type": "String",
"name": "platform",
"meta": {
"added": [
"v0.1.16"
]
},
"desc": "The process.platform
property returns a string identifying the operating\nsystem platform on which the Node.js process is running. For instance\n'darwin'
, 'freebsd'
, 'linux'
, 'sunos'
or 'win32'
console.log(`This platform is ${process.platform}`);\n
\n"
},
{
"textRaw": "process.release",
"name": "release",
"meta": {
"added": [
"v3.0.0"
]
},
"desc": "The process.release
property returns an Object containing metadata related to\nthe current release, including URLs for the source tarball and headers-only\ntarball.
process.release
contains the following properties:
name
{String} A value that will always be 'node'
for Node.js. For\nlegacy io.js releases, this will be 'io.js'
.sourceUrl
{String} an absolute URL pointing to a .tar.gz
file containing\nthe source code of the current release.headersUrl
{String} an absolute URL pointing to a .tar.gz
file containing\nonly the source header files for the current release. This file is\nsignificantly smaller than the full source file and can be used for compiling\nNode.js native add-ons.libUrl
{String} an absolute URL pointing to a node.lib
file matching the\narchitecture and version of the current release. This file is used for\ncompiling Node.js native add-ons. This property is only present on Windows\nbuilds of Node.js and will be missing on all other platforms.lts
{String} a string label identifying the LTS label for this release.\nIf the Node.js release is not an LTS release, this will be undefined
.For example:
\n{\n name: 'node',\n lts: 'Argon',\n sourceUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5.tar.gz',\n headersUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5-headers.tar.gz',\n libUrl: 'https://nodejs.org/download/release/v4.4.5/win-x64/node.lib'\n}\n
\nIn 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.
The process.stderr
property returns a Writable stream equivalent to or\nassociated with stderr
(fd 2
).
Note: process.stderr
and process.stdout
differ from other Node.js streams\nin several ways:
end()
will throw).'finish'
event.To check if Node.js is being run in a TTY context, read the isTTY
property\non process.stderr
, process.stdout
, or process.stdin
:
The process.stdin
property returns a Readable stream equivalent to or\nassociated with stdin
(fd 0
).
For example:
\nprocess.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
\nAs a Readable stream, process.stdin
can also be used in "old" mode that\nis compatible with scripts written for Node.js prior to v0.10.\nFor more information see Stream compatibility.
Note: In "old" streams mode the stdin
stream is paused by default, so one\nmust call process.stdin.resume()
to read from it. Note also that calling\nprocess.stdin.resume()
itself would switch stream to "old" mode.
The process.stdout
property returns a Writable stream equivalent to or\nassociated with stdout
(fd 1
).
For example:
\nconsole.log = (msg) => {\n process.stdout.write(`${msg}\\n`);\n};\n
\nNote: process.stderr
and process.stdout
differ from other Node.js streams\nin several ways:
end()
will throw).'finish'
event.To check if Node.js is being run in a TTY context, read the isTTY
property\non process.stderr
, process.stdout
, or process.stdin
:
The process.stderr
and process.stdout
streams are blocking when outputting\nto TTYs (terminals) on OS X as a workaround for the operating system's small,\n1kb buffer size. This is to prevent interleaving between stdout
and stderr
.
To check if Node.js is being run in a TTY context, check the isTTY
\nproperty on process.stderr
, process.stdout
, or process.stdin
.
For instance:
\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
\nSee the TTY documentation for more information.
\n" } ] }, { "textRaw": "`title` {String} ", "type": "String", "name": "title", "meta": { "added": [ "v0.1.104" ] }, "desc": "The process.title
property returns the current process title (i.e. returns\nthe current value of ps
). Assigning a new value to process.title
modifies\nthe current value of ps
.
Note: When a new value is assigned, different platforms will impose different\nmaximum length restrictions on the title. Usually such restrictions are quite\nlimited. For instance, on Linux and OS X, process.title
is limited to the size\nof the binary name plus the length of the command line arguments because setting\nthe process.title
overwrites the argv
memory of the process. Node.js v0.8\nallowed for longer process title strings by also overwriting the environ
\nmemory but that was potentially insecure and confusing in some (rather obscure)\ncases.
The process.version
property returns the Node.js version string.
console.log(`Version: ${process.version}`);\n
\n"
},
{
"textRaw": "`versions` {Object} ",
"type": "Object",
"name": "versions",
"meta": {
"added": [
"v0.2.0"
]
},
"desc": "The process.versions
property returns an object listing the version strings of\nNode.js and its dependencies. process.versions.modules
indicates the current\nABI version, which is increased whenever a C++ API changes. Node.js will refuse\nto load modules that were compiled against a different module ABI version.
console.log(process.versions);\n
\nWill generate output similar to:
\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 unicode: '8.0',\n cldr: '29.0',\n tz: '2016b' }\n
\n"
}
]
}
],
"vars": [
{
"textRaw": "\\_\\_dirname",
"name": "\\_\\_dirname",
"meta": {
"added": [
"v0.1.27"
]
},
"type": "var",
"desc": "The directory name of the current module. This the same as the\npath.dirname()
of the __filename
.
__dirname
is not actually a global but rather local to each module.
Example: running node example.js
from /Users/mjr
console.log(__dirname);\n// Prints: /Users/mjr\nconsole.log(path.dirname(__filename));\n// Prints: /Users/mjr\n
\n"
},
{
"textRaw": "\\_\\_filename",
"name": "\\_\\_filename",
"meta": {
"added": [
"v0.0.1"
]
},
"type": "var",
"desc": "The file name of the current module. This is the resolved absolute path of the\ncurrent module file.
\nFor a main program this is not necessarily the same as the file name used in the\ncommand line.
\nSee __dirname
for the directory name of the current module.
__filename
is not actually a global but rather local to each module.
Examples:
\nRunning node example.js
from /Users/mjr
console.log(__filename);\n// Prints: /Users/mjr/example.js\nconsole.log(__dirname);\n// Prints: /Users/mjr\n
\nGiven two modules: a
and b
, where b
is a dependency of\na
and there is a directory structure of:
/Users/mjr/app/a.js
/Users/mjr/app/node_modules/b/b.js
References to __filename
within b.js
will return\n/Users/mjr/app/node_modules/b/b.js
while references to __filename
within\na.js
will return /Users/mjr/app/a.js
.
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
.
exports
is not actually a global but rather local to each module.
See the module system documentation for more information.
\n" }, { "textRaw": "module", "name": "module", "meta": { "added": [ "v0.1.16" ] }, "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()
.
module
is not actually a global but rather local to each module.
See the module system documentation for more information.
\n" }, { "textRaw": "require()", "type": "var", "name": "require", "meta": { "added": [ "v0.1.13" ] }, "desc": "To require modules. See the Modules section. require
is not actually a\nglobal but rather local to each module.
Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require
will reload the module. Note that\nthis does not apply to native addons, for which reloading will result in an\nError.
Instruct require
on how to handle certain file extensions.
Process files with the extension .sjs
as .js
:
require.extensions['.sjs'] = require.extensions['.js'];\n
\nDeprecated In the past, this list has been used to load\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.
\nSince 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.
\nNote that the number of file system operations that the module system\nhas to perform in order to resolve a require(...)
statement to a\nfilename scales linearly with the number of registered extensions.
In other words, adding extensions slows down the module loader and\nshould be discouraged.
\n" } ], "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "meta": { "added": [ "v0.3.0" ] }, "desc": "Use the internal require()
machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.
Node.js Addons are dynamically-linked shared objects, written in C or C++, that\ncan be loaded into Node.js using the require()
function, and used\njust as if they were an ordinary Node.js module. They are used primarily to\nprovide an interface between JavaScript running in Node.js and C/C++ libraries.
At the moment, the method for implementing Addons is rather complicated,\ninvolving knowledge of several components and APIs :
\nV8: the C++ library Node.js currently uses to provide the\nJavaScript implementation. V8 provides the mechanisms for creating objects,\ncalling functions, etc. V8's API is documented mostly in the\nv8.h
header file (deps/v8/include/v8.h
in the Node.js source\ntree), which is also available online.
libuv: The C library that implements the Node.js event loop, its worker\nthreads and all of the asynchronous behaviors of the platform. It also\nserves as a cross-platform abstraction library, giving easy, POSIX-like\naccess across all major operating systems to many common system tasks, such\nas interacting with the filesystem, sockets, timers and system events. libuv\nalso provides a pthreads-like threading abstraction that may be used to\npower more sophisticated asynchronous Addons that need to move beyond the\nstandard event loop. Addon authors are encouraged to think about how to\navoid blocking the event loop with I/O or other time-intensive tasks by\noff-loading work via libuv to non-blocking system operations, worker threads\nor a custom use of libuv's threads.
\nInternal Node.js libraries. Node.js itself exports a number of C/C++ APIs\nthat Addons can use — the most important of which is the\nnode::ObjectWrap
class.
Node.js includes a number of other statically linked libraries including\nOpenSSL. These other libraries are located in the deps/
directory in the\nNode.js source tree. Only the V8 and OpenSSL symbols are purposefully\nre-exported by Node.js and may be used to various extents by Addons.\nSee Linking to Node.js' own dependencies for additional information.
All of the following examples are available for download and may\nbe used as a starting-point for your own Addon.
\n", "modules": [ { "textRaw": "Hello world", "name": "hello_world", "desc": "This "Hello world" example is a simple Addon, written in C++, that is the\nequivalent of the following JavaScript code:
\nmodule.exports.hello = () => 'world';\n
\nFirst, create the file hello.cc
:
// hello.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::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
\nNote that all Node.js Addons must export an initialization function following\nthe pattern:
\nvoid Initialize(Local<Object> exports);\nNODE_MODULE(module_name, Initialize)\n
\nThere is no semi-colon after NODE_MODULE
as it's not a function (see\nnode.h
).
The module_name
must match the filename of the final binary (excluding\nthe .node suffix).
In the hello.cc
example, then, the initialization function is init
and the\nAddon module name is addon
.
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 "targets": [\n {\n "target_name": "addon",\n "sources": [ "hello.cc" ]\n }\n ]\n}\n
\nNote: 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.
Once the binding.gyp
file has been created, use node-gyp configure
to\ngenerate the appropriate project build files for the current platform. This\nwill generate either a Makefile
(on Unix platforms) or a vcxproj
file\n(on Windows) in the build/
directory.
Next, invoke the node-gyp build
command to generate the compiled addon.node
\nfile. This will be put into the build/Release/
directory.
When using npm install
to install a Node.js Addon, npm uses its own bundled\nversion of node-gyp
to perform this same set of actions, generating a\ncompiled version of the Addon for the user's platform on demand.
Once built, the binary Addon can be used from within Node.js by pointing\nrequire()
to the built addon.node
module:
// hello.js\nconst addon = require('./build/Release/addon');\n\nconsole.log(addon.hello());\n// Prints: 'world'\n
\nPlease see the examples below for further information or\nhttps://github.com/arturadib/node-qt for an example in production.
\nBecause the exact path to the compiled Addon binary can vary depending on how\nit is compiled (i.e. sometimes it may be in ./build/Debug/
), Addons can use\nthe bindings package to load the compiled module.
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:
try {\n return require('./build/Release/addon.node');\n} catch (err) {\n return require('./build/Debug/addon.node');\n}\n
\n",
"type": "module",
"displayName": "Building"
},
{
"textRaw": "Linking to Node.js' own dependencies",
"name": "linking_to_node.js'_own_dependencies",
"desc": "Node.js uses a number of statically linked libraries such as V8, libuv and\nOpenSSL. All Addons are required to link to V8 and may link to any of the\nother dependencies as well. Typically, this is as simple as including\nthe appropriate #include <...>
statements (e.g. #include <v8.h>
) and\nnode-gyp
will locate the appropriate headers automatically. However, there\nare a few caveats to be aware of:
When node-gyp
runs, it will detect the specific release version of Node.js\nand download either the full source tarball or just the headers. If the full\nsource is downloaded, Addons will have complete access to the full set of\nNode.js dependencies. However, if only the Node.js headers are downloaded, then\nonly the symbols exported by Node.js will be available.
node-gyp
can be run using the --nodedir
flag pointing at a local Node.js\nsource image. Using this option, the Addon will have access to the full set of\ndependencies.
The filename extension of the compiled Addon binary is .node
(as opposed\nto .dll
or .so
). The require()
function is written to look for\nfiles with the .node
file extension and initialize those as dynamically-linked\nlibraries.
When calling require()
, the .node
extension can usually be\nomitted and Node.js will still find and initialize the Addon. One caveat,\nhowever, is that Node.js will first attempt to locate and load modules or\nJavaScript files that happen to share the same base name. For instance, if\nthere is a file addon.js
in the same directory as the binary addon.node
,\nthen require('addon')
will give precedence to the addon.js
file\nand load it instead.
Following are some example Addons intended to help developers get started. The\nexamples make use of the V8 APIs. Refer to the online V8 reference\nfor help with the various V8 calls, and V8's Embedder's Guide for an\nexplanation of several concepts used such as handles, scopes, function\ntemplates, etc.
\nEach of these examples using the following binding.gyp
file:
{\n "targets": [\n {\n "target_name": "addon",\n "sources": [ "addon.cc" ]\n }\n ]\n}\n
\nIn cases where there is more than one .cc
file, simply add the additional\nfilename to the sources
array. For example:
"sources": ["addon.cc", "myexample.cc"]\n
\nOnce the binding.gyp
file is ready, the example Addons can be configured and\nbuilt using node-gyp
:
$ node-gyp configure build\n
\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.
\nThe following example illustrates how to read function arguments passed from\nJavaScript and how to return a result:
\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Exception;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\n// This is the implementation of the "add" method\n// Input arguments are passed using the\n// const FunctionCallbackInfo<Value>& args struct\nvoid Add(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n // Check the number of arguments passed.\n if (args.Length() < 2) {\n // Throw an Error that is passed back to JavaScript\n isolate->ThrowException(Exception::TypeError(\n String::NewFromUtf8(isolate, "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
\nOnce compiled, the example Addon can be required and used from within Node.js:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconsole.log('This should be eight:', addon.add(3, 5));\n
\n",
"type": "module",
"displayName": "Function arguments"
},
{
"textRaw": "Callbacks",
"name": "callbacks",
"desc": "It is common practice within Addons to pass JavaScript functions to a C++\nfunction and execute them from there. The following example illustrates how\nto invoke such callbacks:
\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Null;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid RunCallback(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n Local<Function> cb = Local<Function>::Cast(args[0]);\n const unsigned argc = 1;\n Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") };\n cb->Call(Null(isolate), argc, argv);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n NODE_SET_METHOD(module, "exports", RunCallback);\n}\n\nNODE_MODULE(addon, Init)\n\n} // namespace demo\n
\nNote 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
.
To test it, run the following JavaScript:
\n// test.js\nconst addon = require('./build/Release/addon');\n\naddon((msg) => {\n console.log(msg);\n// Prints: 'hello world'\n});\n
\nNote that, in this example, the callback function is invoked synchronously.
\n", "type": "module", "displayName": "Callbacks" }, { "textRaw": "Object factory", "name": "object_factory", "desc": "Addons can create and return new objects from within a C++ function as\nillustrated in the following example. An object is created and returned with a\nproperty msg
that echoes the string passed to createObject()
:
// 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
\nTo test it in JavaScript:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon('hello');\nconst obj2 = addon('world');\nconsole.log(obj1.msg, obj2.msg);\n// Prints: 'hello world'\n
\n",
"type": "module",
"displayName": "Object factory"
},
{
"textRaw": "Function factory",
"name": "function_factory",
"desc": "Another common scenario is creating JavaScript functions that wrap C++\nfunctions and returning those back to JavaScript:
\n// addon.cc\n#include <node.h>\n\nnamespace demo {\n\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid MyFunction(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));\n}\n\nvoid CreateFunction(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);\n Local<Function> fn = tpl->GetFunction();\n\n // omit this to make it anonymous\n fn->SetName(String::NewFromUtf8(isolate, "theFunction"));\n\n args.GetReturnValue().Set(fn);\n}\n\nvoid Init(Local<Object> exports, Local<Object> module) {\n NODE_SET_METHOD(module, "exports", CreateFunction);\n}\n\nNODE_MODULE(addon, Init)\n\n} // namespace demo\n
\nTo test:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst fn = addon();\nconsole.log(fn());\n// Prints: 'hello world'\n
\n",
"type": "module",
"displayName": "Function factory"
},
{
"textRaw": "Wrapping C++ objects",
"name": "wrapping_c++_objects",
"desc": "It is also possible to wrap C++ objects/classes in a way that allows new\ninstances to be created using the JavaScript new
operator:
// 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
\nThen, in myobject.h
, the wrapper class inherits from node::ObjectWrap
:
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init(v8::Local<v8::Object> exports);\n\n private:\n explicit MyObject(double value = 0);\n ~MyObject();\n\n static void New(const v8::FunctionCallbackInfo<v8::Value>& args);\n static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);\n static v8::Persistent<v8::Function> constructor;\n double value_;\n};\n\n} // namespace demo\n\n#endif\n
\nIn 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:
// myobject.cc\n#include "myobject.h"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Local<Object> exports) {\n Isolate* isolate = exports->GetIsolate();\n\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n // Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);\n\n constructor.Reset(isolate, tpl->GetFunction());\n exports->Set(String::NewFromUtf8(isolate, "MyObject"),\n tpl->GetFunction());\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n // Invoked as constructor: `new MyObject(...)`\n double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n MyObject* obj = new MyObject(value);\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n // Invoked as plain function `MyObject(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Object> result =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(result);\n }\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());\n obj->value_ += 1;\n\n args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n} // namespace demo\n
\nTo build this example, the myobject.cc
file must be added to the\nbinding.gyp
:
{\n "targets": [\n {\n "target_name": "addon",\n "sources": [\n "addon.cc",\n "myobject.cc"\n ]\n }\n ]\n}\n
\nTest it with:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj = new addon.MyObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n
\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:
const obj = addon.createObject();\n// instead of:\n// const obj = new addon.Object();\n
\nFirst, the createObject()
method is implemented in addon.cc
:
// addon.cc\n#include <node.h>\n#include "myobject.h"\n\nnamespace demo {\n\nusing v8::FunctionCallbackInfo;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::String;\nusing v8::Value;\n\nvoid CreateObject(const FunctionCallbackInfo<Value>& args) {\n MyObject::NewInstance(args);\n}\n\nvoid InitAll(Local<Object> exports, Local<Object> module) {\n MyObject::Init(exports->GetIsolate());\n\n NODE_SET_METHOD(module, "exports", CreateObject);\n}\n\nNODE_MODULE(addon, InitAll)\n\n} // namespace demo\n
\nIn myobject.h
, the static method NewInstance()
is added to handle\ninstantiating the object. This method takes the place of using new
in\nJavaScript:
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init(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
\nThe implementation in myobject.cc
is similar to the previous example:
// myobject.cc\n#include <node.h>\n#include "myobject.h"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Number;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Isolate* isolate) {\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n // Prototype\n NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);\n\n constructor.Reset(isolate, tpl->GetFunction());\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n // Invoked as constructor: `new MyObject(...)`\n double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n MyObject* obj = new MyObject(value);\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n // Invoked as plain function `MyObject(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Context> context = isolate->GetCurrentContext();\n Local<Object> instance =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(instance);\n }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n const unsigned argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Context> context = isolate->GetCurrentContext();\n Local<Object> instance =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n args.GetReturnValue().Set(instance);\n}\n\nvoid MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());\n obj->value_ += 1;\n\n args.GetReturnValue().Set(Number::New(isolate, obj->value_));\n}\n\n} // namespace demo\n
\nOnce again, to build this example, the myobject.cc
file must be added to the\nbinding.gyp
:
{\n "targets": [\n {\n "target_name": "addon",\n "sources": [\n "addon.cc",\n "myobject.cc"\n ]\n }\n ]\n}\n
\nTest it with:
\n// test.js\nconst createObject = require('./build/Release/addon');\n\nconst obj = createObject(10);\nconsole.log(obj.plusOne());\n// Prints: 11\nconsole.log(obj.plusOne());\n// Prints: 12\nconsole.log(obj.plusOne());\n// Prints: 13\n\nconst obj2 = createObject(20);\nconsole.log(obj2.plusOne());\n// Prints: 21\nconsole.log(obj2.plusOne());\n// Prints: 22\nconsole.log(obj2.plusOne());\n// Prints: 23\n
\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:
// 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
\nIn myobject.h
, a new public method is added to allow access to private values\nafter unwrapping the object.
// myobject.h\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n#include <node_object_wrap.h>\n\nnamespace demo {\n\nclass MyObject : public node::ObjectWrap {\n public:\n static void Init(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
\nThe implementation of myobject.cc
is similar to before:
// myobject.cc\n#include <node.h>\n#include "myobject.h"\n\nnamespace demo {\n\nusing v8::Context;\nusing v8::Function;\nusing v8::FunctionCallbackInfo;\nusing v8::FunctionTemplate;\nusing v8::Isolate;\nusing v8::Local;\nusing v8::Object;\nusing v8::Persistent;\nusing v8::String;\nusing v8::Value;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Isolate* isolate) {\n // Prepare constructor template\n Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);\n tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n constructor.Reset(isolate, tpl->GetFunction());\n}\n\nvoid MyObject::New(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n if (args.IsConstructCall()) {\n // Invoked as constructor: `new MyObject(...)`\n double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n MyObject* obj = new MyObject(value);\n obj->Wrap(args.This());\n args.GetReturnValue().Set(args.This());\n } else {\n // Invoked as plain function `MyObject(...)`, turn into construct call.\n const int argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Context> context = isolate->GetCurrentContext();\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Object> instance =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n args.GetReturnValue().Set(instance);\n }\n}\n\nvoid MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {\n Isolate* isolate = args.GetIsolate();\n\n const unsigned argc = 1;\n Local<Value> argv[argc] = { args[0] };\n Local<Function> cons = Local<Function>::New(isolate, constructor);\n Local<Context> context = isolate->GetCurrentContext();\n Local<Object> instance =\n cons->NewInstance(context, argc, argv).ToLocalChecked();\n\n args.GetReturnValue().Set(instance);\n}\n\n} // namespace demo\n
\nTest it with:
\n// test.js\nconst addon = require('./build/Release/addon');\n\nconst obj1 = addon.createObject(10);\nconst obj2 = addon.createObject(20);\nconst result = addon.add(obj1, obj2);\n\nconsole.log(result);\n// Prints: 30\n
\n",
"type": "module",
"displayName": "Passing wrapped objects around"
},
{
"textRaw": "AtExit hooks",
"name": "atexit_hooks",
"desc": "An "AtExit" hook is a function that is invoked after the Node.js event loop\nhas ended but before the JavaScript VM is terminated and Node.js shuts down.\n"AtExit" hooks are registered using the node::AtExit
API.
callback
: void (*)(void*)
- A pointer to the function to call at exit.args
: void*
- A pointer to pass to the callback at exit.Registers exit hooks that run after the event loop has ended but before the VM\nis killed.
\nAtExit 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.
\nCallbacks are run in last-in first-out order.
\nThe following addon.cc
implements AtExit:
// 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
\nTest in JavaScript by running:
\n// test.js\nconst addon = require('./build/Release/addon');\n
\n\n\n",
"type": "module",
"displayName": "void AtExit(callback, args)"
}
],
"type": "module",
"displayName": "AtExit hooks"
}
],
"type": "module",
"displayName": "Addon examples"
}
],
"properties": [
{
"textRaw": "Native Abstractions for Node.js",
"name": "js",
"desc": "Each of the examples illustrated in this document make direct use of the\nNode.js and V8 APIs for implementing Addons. It is important to understand\nthat the V8 API can, and has, changed dramatically from one V8 release to the\nnext (and one major Node.js release to the next). With each change, Addons may\nneed to be updated and recompiled in order to continue functioning. The Node.js\nrelease schedule is designed to minimize the frequency and impact of such\nchanges but there is little that Node.js can do currently to ensure stability\nof the V8 APIs.
\nThe Native Abstractions for Node.js (or nan
) provide a set of tools that\nAddon developers are recommended to use to keep compatibility between past and\nfuture releases of V8 and Node.js. See the nan
examples for an\nillustration of how it can be used.
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.
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.
An alias of assert.ok()
.
const assert = require('assert');\n\nassert(true);\n// OK\nassert(1);\n// 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
\n",
"signatures": [
{
"params": [
{
"name": "value"
},
{
"name": "message",
"optional": true
}
]
}
]
},
{
"textRaw": "assert.deepEqual(actual, expected[, message])",
"type": "method",
"name": "deepEqual",
"meta": {
"added": [
"v0.1.21"
]
},
"desc": "Tests for deep equality between the actual
and expected
parameters.\nPrimitive values are compared with the equal comparison operator ( ==
).
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:
// WARNING: This does not throw an AssertionError!\nassert.deepEqual(Error('a'), Error('b'));\n
\n"Deep" equality means that the enumerable "own" properties of child objects\nare evaluated also:
\nconst 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
\nIf the values are not equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned.
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.
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
\nIf the values are not equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned.
Asserts that the function block
does not throw an error. See\nassert.throws()
for more details.
When assert.doesNotThrow()
is called, it will immediately call the block
\nfunction.
If an error is thrown and it is the same type as that specified by the error
\nparameter, then an AssertionError
is thrown. If the error is of a different\ntype, or if the error
parameter is undefined, the error is propagated back\nto the caller.
The following, for instance, will throw the TypeError
because there is no\nmatching error type in the assertion:
assert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n SyntaxError\n);\n
\nHowever, the following will result in an AssertionError
with the message\n'Got unwanted exception (TypeError)..':
assert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n TypeError\n);\n
\nIf an AssertionError
is thrown and a value is provided for the message
\nparameter, the value of message
will be appended to the AssertionError
\nmessage:
assert.doesNotThrow(\n () => {\n throw new TypeError('Wrong value');\n },\n TypeError,\n 'Whoops'\n);\n// Throws: AssertionError: Got unwanted exception (TypeError). Whoops\n
\n",
"signatures": [
{
"params": [
{
"name": "block"
},
{
"name": "error",
"optional": true
},
{
"name": "message",
"optional": true
}
]
}
]
},
{
"textRaw": "assert.equal(actual, expected[, message])",
"type": "method",
"name": "equal",
"meta": {
"added": [
"v0.1.21"
]
},
"desc": "Tests shallow, coercive equality between the actual
and expected
parameters\nusing the equal comparison operator ( ==
).
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
\nIf the values are not equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned.
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
.
const assert = require('assert');\n\nassert.fail(1, 2, undefined, '>');\n// AssertionError: 1 > 2\n\nassert.fail(1, 2, 'whoops', '>');\n// AssertionError: whoops\n
\n",
"signatures": [
{
"params": [
{
"name": "actual"
},
{
"name": "expected"
},
{
"name": "message"
},
{
"name": "operator"
}
]
}
]
},
{
"textRaw": "assert.ifError(value)",
"type": "method",
"name": "ifError",
"meta": {
"added": [
"v0.1.97"
]
},
"desc": "Throws value
if value
is truthy. This is useful when testing the error
\nargument in callbacks.
const assert = require('assert');\n\nassert.ifError(0);\n// OK\nassert.ifError(1);\n// Throws 1\nassert.ifError('error');\n// Throws 'error'\nassert.ifError(new Error());\n// Throws Error\n
\n",
"signatures": [
{
"params": [
{
"name": "value"
}
]
}
]
},
{
"textRaw": "assert.notDeepEqual(actual, expected[, message])",
"type": "method",
"name": "notDeepEqual",
"meta": {
"added": [
"v0.1.21"
]
},
"desc": "Tests for any deep inequality. Opposite of assert.deepEqual()
.
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
\nIf 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.
Tests for deep strict inequality. Opposite of assert.deepStrictEqual()
.
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
\nIf the values are deeply and strictly equal, an AssertionError
is thrown\nwith a message
property set equal to the value of the message
parameter. If\nthe message
parameter is undefined, a default error message is assigned.
Tests shallow, coercive inequality with the not equal comparison operator\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
\nIf the values are equal, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined, a default error message is assigned.
Tests strict inequality as determined by the strict not equal operator\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
\nIf the values are strictly equal, an AssertionError
is thrown with a\nmessage
property set equal to the value of the message
parameter. If the\nmessage
parameter is undefined, a default error message is assigned.
Tests if value
is truthy. It is equivalent to\nassert.equal(!!value, true, message)
.
If value
is not truthy, an AssertionError
is thrown with a message
\nproperty set equal to the value of the message
parameter. If the message
\nparameter is undefined
, a default error message is assigned.
const assert = require('assert');\n\nassert.ok(true);\n// OK\nassert.ok(1);\n// OK\nassert.ok(false);\n// throws "AssertionError: false == true"\nassert.ok(0);\n// throws "AssertionError: 0 == true"\nassert.ok(false, 'it\\'s false');\n// throws "AssertionError: it's false"\n
\n",
"signatures": [
{
"params": [
{
"name": "value"
},
{
"name": "message",
"optional": true
}
]
}
]
},
{
"textRaw": "assert.strictEqual(actual, expected[, message])",
"type": "method",
"name": "strictEqual",
"meta": {
"added": [
"v0.1.21"
]
},
"desc": "Tests strict equality as determined by the strict equality operator ( ===
).
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
\nIf the values are not strictly equal, an AssertionError
is thrown with a\nmessage
property set equal to the value of the message
parameter. If the\nmessage
parameter is undefined, a default error message is assigned.
Expects the function block
to throw an error.
If specified, error
can be a constructor, RegExp
, or validation\nfunction.
If specified, message
will be the message provided by the AssertionError
if\nthe block fails to throw.
Validate instanceof using constructor:
\nassert.throws(\n () => {\n throw new Error('Wrong value');\n },\n Error\n);\n
\nValidate error message using RegExp
:
assert.throws(\n () => {\n throw new Error('Wrong value');\n },\n /value/\n);\n
\nCustom error validation:
\nassert.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
\nNote 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:
// THIS IS A MISTAKE! DO NOT DO THIS!\nassert.throws(myFunction, 'missing foo', 'did not throw with expected message');\n\n// Do this instead.\nassert.throws(myFunction, /missing foo/, 'did not throw with expected message');\n
\n\n\n",
"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.
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.
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.
The Buffer
class is a global within Node.js, making it unlikely that one\nwould need to ever use require('buffer').Buffer
.
Examples:
\n// Creates a zero-filled Buffer of length 10.\nconst buf1 = Buffer.alloc(10);\n\n// Creates a Buffer of length 10, filled with 0x1.\nconst buf2 = Buffer.alloc(10, 1);\n\n// Creates an uninitialized buffer of length 10.\n// This is faster than calling Buffer.alloc() but the returned\n// Buffer instance might contain old data that needs to be\n// overwritten using either fill() or write().\nconst buf3 = Buffer.allocUnsafe(10);\n\n// Creates a Buffer containing [0x1, 0x2, 0x3].\nconst buf4 = Buffer.from([1, 2, 3]);\n\n// Creates a Buffer containing ASCII bytes [0x74, 0x65, 0x73, 0x74].\nconst buf5 = Buffer.from('test');\n\n// Creates a Buffer containing UTF-8 bytes [0x74, 0xc3, 0xa9, 0x73, 0x74].\nconst buf6 = Buffer.from('tést', 'utf8');\n
\n",
"modules": [
{
"textRaw": "`Buffer.from()`, `Buffer.alloc()`, and `Buffer.allocUnsafe()`",
"name": "`buffer.from()`,_`buffer.alloc()`,_and_`buffer.allocunsafe()`",
"desc": "In versions of Node.js prior to v6, Buffer
instances were created using the\nBuffer
constructor function, which allocates the returned Buffer
\ndifferently based on what arguments are provided:
Buffer()
(e.g. new Buffer(10)
),\nallocates a new Buffer
object of the specified size. The memory allocated\nfor such Buffer
instances is not initialized and can contain sensitive\ndata. Such Buffer
instances must be initialized manually by using either\nbuf.fill(0)
or by writing to the Buffer
completely. While\nthis behavior is intentional to improve performance, development experience\nhas demonstrated that a more explicit distinction is required between creating\na fast-but-uninitialized Buffer
versus creating a slower-but-safer Buffer
.Buffer
as the first argument copies the\npassed object's data into the Buffer
.ArrayBuffer
returns a Buffer
that shares allocated memory with\nthe given ArrayBuffer
.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.
To make the creation of Buffer
instances more reliable and less error prone,\nthe various forms of the new Buffer()
constructor have been deprecated\nand replaced by separate Buffer.from()
, Buffer.alloc()
, and\nBuffer.allocUnsafe()
methods.
Developers should migrate all existing uses of the new Buffer()
constructors\nto one of these new APIs.
Buffer.from(array)
returns a new Buffer
containing a copy of the provided\noctets.Buffer.from(arrayBuffer[, byteOffset [, length]])
\nreturns a new Buffer
that shares the same allocated memory as the given\nArrayBuffer
.Buffer.from(buffer)
returns a new Buffer
containing a copy of the\ncontents of the given Buffer
.Buffer.from(string[, encoding])
returns a new Buffer
\ncontaining a copy of the provided string.Buffer.alloc(size[, fill[, encoding]])
returns a "filled"\nBuffer
instance of the specified size. This method can be significantly\nslower than Buffer.allocUnsafe(size)
but ensures\nthat newly created Buffer
instances never contain old and potentially\nsensitive data.Buffer.allocUnsafe(size)
and\nBuffer.allocUnsafeSlow(size)
each return a\nnew Buffer
of the specified size
whose content must be initialized\nusing either buf.fill(0)
or written to completely.Buffer
instances returned by Buffer.allocUnsafe()
may be allocated off\na shared internal memory pool if size
is less than or equal to half\nBuffer.poolSize
. Instances returned by Buffer.allocUnsafeSlow()
never\nuse the shared internal memory pool.
Node.js can be started using the --zero-fill-buffers
command line option to\nforce all newly allocated Buffer
instances created using either\nnew Buffer(size)
, Buffer.allocUnsafe()
, Buffer.allocUnsafeSlow()
or\nnew SlowBuffer(size)
to be automatically zero-filled upon creation. Use of\nthis flag changes the default behavior of these methods and can have a significant\nimpact on performance. Use of the --zero-fill-buffers
option is recommended\nonly when necessary to enforce that newly allocated Buffer
instances cannot\ncontain potentially sensitive data.
Example:
\n$ node --zero-fill-buffers\n> Buffer.allocUnsafe(5);\n<Buffer 00 00 00 00 00>\n
\n",
"type": "module",
"displayName": "The `--zero-fill-buffers` command line option"
},
{
"textRaw": "What makes `Buffer.allocUnsafe()` and `Buffer.allocUnsafeSlow()` \"unsafe\"?",
"name": "what_makes_`buffer.allocunsafe()`_and_`buffer.allocunsafeslow()`_\"unsafe\"?",
"desc": "When calling Buffer.allocUnsafe()
and Buffer.allocUnsafeSlow()
, the\nsegment of allocated memory is uninitialized (it is not zeroed-out). While\nthis design makes the allocation of memory quite fast, the allocated segment of\nmemory might contain old data that is potentially sensitive. Using a Buffer
\ncreated by Buffer.allocUnsafe()
without completely overwriting the memory\ncan allow this old data to be leaked when the Buffer
memory is read.
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.
Buffer
instances are commonly used to represent sequences of encoded characters\nsuch as UTF-8, UCS2, Base64 or even Hex-encoded data. It is possible to\nconvert back and forth between Buffer
instances and ordinary JavaScript strings\nby using an explicit character encoding.
Example:
\nconst buf = Buffer.from('hello world', 'ascii');\n\n// Prints: 68656c6c6f20776f726c64\nconsole.log(buf.toString('hex'));\n\n// Prints: aGVsbG8gd29ybGQ=\nconsole.log(buf.toString('base64'));\n
\nThe character encodings currently supported by Node.js include:
\n'ascii'
- for 7-bit ASCII data only. This encoding is fast and will strip\nthe high bit if set.
'utf8'
- Multibyte encoded Unicode characters. Many web pages and other\ndocument formats use UTF-8.
'utf16le'
- 2 or 4 bytes, little-endian encoded Unicode characters.\nSurrogate pairs (U+10000 to U+10FFFF) are supported.
'ucs2'
- Alias of 'utf16le'
.
'base64'
- Base64 encoding. When creating a Buffer
from a string,\nthis encoding will also correctly accept "URL and Filename Safe Alphabet" as\nspecified in RFC4648, Section 5.
'latin1'
- A way of encoding the Buffer
into a one-byte encoded string\n(as defined by the IANA in RFC1345,\npage 63, to be the Latin-1 supplement block and C0/C1 control codes).
'binary'
- Alias for 'latin1'
.
'hex'
- Encode each byte as two hexadecimal characters.
Note: Today's browsers follow the WHATWG spec which aliases both 'latin1' and\nISO-8859-1 to win-1252. This means that while doing something like http.get()
,\nif the returned charset is one of those listed in the WHATWG spec it's possible\nthat the server actually returned win-1252-encoded data, and using 'latin1'
\nencoding may incorrectly decode the characters.
Buffer
instances are also Uint8Array
instances. However, there are subtle\nincompatibilities with the TypedArray specification in ECMAScript 2015.\nFor example, while ArrayBuffer#slice()
creates a copy of the slice, the\nimplementation of Buffer#slice()
creates a view over the\nexisting Buffer
without copying, making Buffer#slice()
far\nmore efficient.
It is also possible to create new TypedArray
instances from a Buffer
with\nthe following caveats:
The Buffer
object's memory is copied to the TypedArray
, not shared.
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]
.
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.
Example:
\nconst arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Copies the contents of `arr`\nconst buf1 = Buffer.from(arr);\n\n// Shares memory with `arr`\nconst buf2 = Buffer.from(arr.buffer);\n\n// Prints: <Buffer 88 a0>\nconsole.log(buf1);\n\n// Prints: <Buffer 88 13 a0 0f>\nconsole.log(buf2);\n\narr[1] = 6000;\n\n// Prints: <Buffer 88 a0>\nconsole.log(buf1);\n\n// Prints: <Buffer 88 13 70 17>\nconsole.log(buf2);\n
\nNote that when creating a Buffer
using a TypedArray
's .buffer
, it is\npossible to use only a portion of the underlying ArrayBuffer
by passing in\nbyteOffset
and length
parameters.
Example:
\nconst arr = new Uint16Array(20);\nconst buf = Buffer.from(arr.buffer, 0, 16);\n\n// Prints: 16\nconsole.log(buf.length);\n
\nThe Buffer.from()
and TypedArray.from()
have different signatures and\nimplementations. Specifically, the TypedArray
variants accept a second\nargument that is a mapping function that is invoked on every element of the\ntyped array:
TypedArray.from(source[, mapFn[, thisArg]])
The Buffer.from()
method, however, does not support the use of a mapping\nfunction:
Buffer.from(array)
Buffer.from(buffer)
Buffer.from(arrayBuffer[, byteOffset [, length]])
Buffer.from(string[, encoding])
Buffer
instances can be iterated over using the ECMAScript 2015 (ES6) for..of
\nsyntax.
Example:
\nconst buf = Buffer.from([1, 2, 3]);\n\n// Prints:\n// 1\n// 2\n// 3\nfor (const b of buf) {\n console.log(b);\n}\n
\nAdditionally, the buf.values()
, buf.keys()
, and\nbuf.entries()
methods can be used to create iterators.
The Buffer
class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.
Allocates a new Buffer
of size
bytes. If fill
is undefined
, the\nBuffer
will be zero-filled.
Example:
\nconst buf = Buffer.alloc(5);\n\n// Prints: <Buffer 00 00 00 00 00>\nconsole.log(buf);\n
\nAllocates a new Buffer
of size
bytes. If the size
is larger than\nbuffer.kMaxLength
or smaller than 0, a RangeError
will be thrown.\nA zero-length Buffer
will be created if size
is 0.
If fill
is specified, the allocated Buffer
will be initialized by calling\nbuf.fill(fill)
.
Example:
\nconst buf = Buffer.alloc(5, 'a');\n\n// Prints: <Buffer 61 61 61 61 61>\nconsole.log(buf);\n
\nIf both fill
and encoding
are specified, the allocated Buffer
will be\ninitialized by calling buf.fill(fill, encoding)
.
Example:
\nconst buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');\n\n// Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>\nconsole.log(buf);\n
\nCalling Buffer.alloc()
can be significantly slower than the alternative\nBuffer.allocUnsafe()
but ensures that the newly created Buffer
instance\ncontents will never contain sensitive data.
A TypeError
will be thrown if size
is not a number.
Allocates a new Buffer
of size
bytes. If the size
is larger than\nbuffer.kMaxLength
or smaller than 0, a RangeError
will be thrown.\nA zero-length Buffer
will be created if size
is 0.
The underlying memory for Buffer
instances created in this way is not\ninitialized. The contents of the newly created Buffer
are unknown and\nmay contain sensitive data. Use Buffer.alloc()
instead to initialize\nBuffer
instances to zeroes.
Example:
\nconst buf = Buffer.allocUnsafe(10);\n\n// Prints: (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\nconsole.log(buf);\n
\nA TypeError
will be thrown if size
is not a number.
Note that the Buffer
module pre-allocates an internal Buffer
instance of\nsize Buffer.poolSize
that is used as a pool for the fast allocation of new\nBuffer
instances created using Buffer.allocUnsafe()
and the deprecated\nnew Buffer(size)
constructor only when size
is less than or equal to\nBuffer.poolSize >> 1
(floor of Buffer.poolSize
divided by two).
Use of this pre-allocated internal memory pool is a key difference between\ncalling Buffer.alloc(size, fill)
vs. Buffer.allocUnsafe(size).fill(fill)
.\nSpecifically, Buffer.alloc(size, fill)
will never use the internal Buffer
\npool, while Buffer.allocUnsafe(size).fill(fill)
will use the internal\nBuffer
pool if size
is less than or equal to half Buffer.poolSize
. The\ndifference is subtle but can be important when an application requires the\nadditional performance that Buffer.allocUnsafe()
provides.
Allocates a new Buffer
of size
bytes. If the size
is larger than\nbuffer.kMaxLength
or smaller than 0, a RangeError
will be thrown.\nA zero-length Buffer
will be created if size
is 0.
The underlying memory for Buffer
instances created in this way is not\ninitialized. The contents of the newly created Buffer
are unknown and\nmay contain sensitive data. Use buf.fill(0)
to initialize such\nBuffer
instances to zeroes.
When using Buffer.allocUnsafe()
to allocate new Buffer
instances,\nallocations under 4KB are, by default, sliced from a single pre-allocated\nBuffer
. This allows applications to avoid the garbage collection overhead of\ncreating many individually allocated Buffer
instances. This approach improves\nboth performance and memory usage by eliminating the need to track and cleanup as\nmany Persistent
objects.
However, in the case where a developer may need to retain a small chunk of\nmemory from a pool for an indeterminate amount of time, it may be appropriate\nto create an un-pooled Buffer
instance using Buffer.allocUnsafeSlow()
then\ncopy out the relevant bits.
Example:
\n// Need to keep around a few small chunks of memory\nconst store = [];\n\nsocket.on('readable', () => {\n const data = socket.read();\n\n // Allocate for retained data\n const sb = Buffer.allocUnsafeSlow(10);\n\n // Copy the data into the new allocation\n data.copy(sb, 0, 0, 10);\n\n store.push(sb);\n});\n
\nUse of Buffer.allocUnsafeSlow()
should be used only as a last resort after\na developer has observed undue memory retention in their applications.
A TypeError
will be thrown if size
is not a number.
Returns the actual byte length of a string. This is not the same as\nString.prototype.length
since that returns the number of characters in\na string.
Example:
\nconst str = '\\u00bd + \\u00bc = \\u00be';\n\n// Prints: ½ + ¼ = ¾: 9 characters, 12 bytes\nconsole.log(`${str}: ${str.length} characters, ` +\n `${Buffer.byteLength(str, 'utf8')} bytes`);\n
\nWhen string
is a Buffer
/DataView
/TypedArray
/ArrayBuffer
, the\nactual byte length is returned.
Compares buf1
to buf2
typically for the purpose of sorting arrays of\nBuffer
instances. This is equivalent to calling\nbuf1.compare(buf2)
.
Example:
\nconst buf1 = Buffer.from('1234');\nconst buf2 = Buffer.from('0123');\nconst arr = [buf1, buf2];\n\n// Prints: [ <Buffer 30 31 32 33>, <Buffer 31 32 33 34> ]\n// (This result is equal to: [buf2, buf1])\nconsole.log(arr.sort(Buffer.compare));\n
\n"
},
{
"textRaw": "Class Method: Buffer.concat(list[, totalLength])",
"type": "classMethod",
"name": "concat",
"meta": {
"added": [
"v0.7.11"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer} ",
"name": "return",
"type": "Buffer"
},
"params": [
{
"textRaw": "`list` {Array} List of `Buffer` instances to concat ",
"name": "list",
"type": "Array",
"desc": "List of `Buffer` instances to concat"
},
{
"textRaw": "`totalLength` {Integer} Total length of the `Buffer` instances in `list` when concatenated ",
"name": "totalLength",
"type": "Integer",
"desc": "Total length of the `Buffer` instances in `list` when concatenated",
"optional": true
}
]
},
{
"params": [
{
"name": "list"
},
{
"name": "totalLength",
"optional": true
}
]
}
],
"desc": "Returns a new Buffer
which is the result of concatenating all the Buffer
\ninstances in the list
together.
If the list has no items, or if the totalLength
is 0, then a new zero-length\nBuffer
is returned.
If totalLength
is not provided, it is calculated from the Buffer
instances\nin list
. This however causes an additional loop to be executed in order to\ncalculate the totalLength
, so it is faster to provide the length explicitly if\nit is already known.
Example: Create a single Buffer
from a list of three Buffer
instances
const buf1 = Buffer.alloc(10);\nconst buf2 = Buffer.alloc(14);\nconst buf3 = Buffer.alloc(18);\nconst totalLength = buf1.length + buf2.length + buf3.length;\n\n// Prints: 42\nconsole.log(totalLength);\n\nconst bufA = Buffer.concat([buf1, buf2, buf3], totalLength);\n\n// Prints: <Buffer 00 00 00 00 ...>\nconsole.log(bufA);\n\n// Prints: 42\nconsole.log(bufA.length);\n
\n"
},
{
"textRaw": "Class Method: Buffer.from(array)",
"type": "classMethod",
"name": "from",
"meta": {
"added": [
"v5.10.0"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`array` {Array} ",
"name": "array",
"type": "Array"
}
]
},
{
"params": [
{
"name": "array"
}
]
}
],
"desc": "Allocates a new Buffer
using an array
of octets.
Example:
\n// Creates a new Buffer containing ASCII bytes of the string 'buffer'\nconst buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n
\nA TypeError
will be thrown if array
is not an Array
.
This creates a view of the ArrayBuffer
without copying the underlying\nmemory. For example, when passed a reference to the .buffer
property of a\nTypedArray
instance, the newly created Buffer
will share the same\nallocated memory as the TypedArray
.
Example:
\nconst arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`\nconst buf = Buffer.from(arr.buffer);\n\n// Prints: <Buffer 88 13 a0 0f>\nconsole.log(buf);\n\n// Changing the original Uint16Array changes the Buffer also\narr[1] = 6000;\n\n// Prints: <Buffer 88 13 70 17>\nconsole.log(buf);\n
\nThe optional byteOffset
and length
arguments specify a memory range within\nthe arrayBuffer
that will be shared by the Buffer
.
Example:
\nconst ab = new ArrayBuffer(10);\nconst buf = Buffer.from(ab, 0, 2);\n\n// Prints: 2\nconsole.log(buf.length);\n
\nA TypeError
will be thrown if arrayBuffer
is not an ArrayBuffer
.
Copies the passed buffer
data onto a new Buffer
instance.
Example:
\nconst buf1 = Buffer.from('buffer');\nconst buf2 = Buffer.from(buf1);\n\nbuf1[0] = 0x61;\n\n// Prints: auffer\nconsole.log(buf1.toString());\n\n// Prints: buffer\nconsole.log(buf2.toString());\n
\nA TypeError
will be thrown if buffer
is not a Buffer
.
Creates a new Buffer
containing the given JavaScript string string
. If\nprovided, the encoding
parameter identifies the character encoding of string
.
Examples:
\nconst buf1 = Buffer.from('this is a tést');\n\n// Prints: this is a tést\nconsole.log(buf1.toString());\n\n// Prints: this is a tC)st\nconsole.log(buf1.toString('ascii'));\n\n\nconst buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');\n\n// Prints: this is a tést\nconsole.log(buf2.toString());\n
\nA TypeError
will be thrown if str
is not a string.
Returns true
if obj
is a Buffer
, false
otherwise.
Returns true
if encoding
contains a supported character encoding, or false
\notherwise.
This is the number of bytes used to determine the size of pre-allocated, internal\nBuffer
instances used for pooling. This value may be modified.
The index operator [index]
can be used to get and set the octet at position\nindex
in buf
. The values refer to individual bytes, so the legal value\nrange is between 0x00
and 0xFF
(hex) or 0
and 255
(decimal).
Example: Copy an ASCII string into a Buffer
, one byte at a time
const str = 'Node.js';\nconst buf = Buffer.allocUnsafe(str.length);\n\nfor (let i = 0; i < str.length ; i++) {\n buf[i] = str.charCodeAt(i);\n}\n\n// Prints: Node.js\nconsole.log(buf.toString('ascii'));\n
\n"
},
{
"textRaw": "`length` {Integer} ",
"type": "Integer",
"name": "length",
"meta": {
"added": [
"v0.1.90"
]
},
"desc": "Returns the amount of memory allocated for buf
in bytes. Note that this\ndoes not necessarily reflect the amount of "usable" data within buf
.
Example: Create a Buffer
and write a shorter ASCII string to it
const buf = Buffer.alloc(1234);\n\n// Prints: 1234\nconsole.log(buf.length);\n\nbuf.write('some string', 0, 'ascii');\n\n// Prints: 1234\nconsole.log(buf.length);\n
\nWhile 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
.
Examples:
\nlet buf = Buffer.allocUnsafe(10);\n\nbuf.write('abcdefghj', 0, 'ascii');\n\n// Prints: 10\nconsole.log(buf.length);\n\nbuf = buf.slice(0, 5);\n\n// Prints: 5\nconsole.log(buf.length);\n
\n"
}
],
"methods": [
{
"textRaw": "buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])",
"type": "method",
"name": "compare",
"meta": {
"added": [
"v0.11.13"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`target` {Buffer} A `Buffer` to compare to ",
"name": "target",
"type": "Buffer",
"desc": "A `Buffer` to compare to"
},
{
"textRaw": "`targetStart` {Integer} The offset within `target` at which to begin comparison. **Default:** `0` ",
"name": "targetStart",
"type": "Integer",
"desc": "The offset within `target` at which to begin comparison. **Default:** `0`",
"optional": true
},
{
"textRaw": "`targetEnd` {Integer} The offset with `target` at which to end comparison (not inclusive). Ignored when `targetStart` is `undefined`. **Default:** `target.length` ",
"name": "targetEnd",
"type": "Integer",
"desc": "The offset with `target` at which to end comparison (not inclusive). Ignored when `targetStart` is `undefined`. **Default:** `target.length`",
"optional": true
},
{
"textRaw": "`sourceStart` {Integer} The offset within `buf` at which to begin comparison. Ignored when `targetStart` is `undefined`. **Default:** `0` ",
"name": "sourceStart",
"type": "Integer",
"desc": "The offset within `buf` at which to begin comparison. Ignored when `targetStart` is `undefined`. **Default:** `0`",
"optional": true
},
{
"textRaw": "`sourceEnd` {Integer} The offset within `buf` at which to end comparison (not inclusive). Ignored when `targetStart` is `undefined`. **Default:** [`buf.length`] ",
"name": "sourceEnd",
"type": "Integer",
"desc": "The offset within `buf` at which to end comparison (not inclusive). Ignored when `targetStart` is `undefined`. **Default:** [`buf.length`]",
"optional": true
}
]
},
{
"params": [
{
"name": "target"
},
{
"name": "targetStart",
"optional": true
},
{
"name": "targetEnd",
"optional": true
},
{
"name": "sourceStart",
"optional": true
},
{
"name": "sourceEnd",
"optional": true
}
]
}
],
"desc": "Compares buf
with target
and returns a number indicating whether buf
\ncomes before, after, or is the same as target
in sort order.\nComparison is based on the actual sequence of bytes in each Buffer
.
0
is returned if target
is the same as buf
1
is returned if target
should come before buf
when sorted.-1
is returned if target
should come after buf
when sorted.Examples:
\nconst buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('BCD');\nconst buf3 = Buffer.from('ABCD');\n\n// Prints: 0\nconsole.log(buf1.compare(buf1));\n\n// Prints: -1\nconsole.log(buf1.compare(buf2));\n\n// Prints: -1\nconsole.log(buf1.compare(buf3));\n\n// Prints: 1\nconsole.log(buf2.compare(buf1));\n\n// Prints: 1\nconsole.log(buf2.compare(buf3));\n\n// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]\n// (This result is equal to: [buf1, buf3, buf2])\nconsole.log([buf1, buf2, buf3].sort(Buffer.compare));\n
\nThe optional targetStart
, targetEnd
, sourceStart
, and sourceEnd
\narguments can be used to limit the comparison to specific ranges within target
\nand buf
respectively.
Examples:
\nconst buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);\nconst buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);\n\n// Prints: 0\nconsole.log(buf1.compare(buf2, 5, 9, 0, 4));\n\n// Prints: -1\nconsole.log(buf1.compare(buf2, 0, 6, 4));\n\n// Prints: 1\nconsole.log(buf1.compare(buf2, 5, 6, 5));\n
\nA RangeError
will be thrown if: targetStart < 0
, sourceStart < 0
,\ntargetEnd > target.byteLength
or sourceEnd > source.byteLength
.
Copies data from a region of buf
to a region in target
even if the target
\nmemory region overlaps with buf
.
Example: Create two Buffer
instances, buf1
and buf2
, and copy buf1
from\nbyte 16 through byte 19 into buf2
, starting at the 8th byte in buf2
const buf1 = Buffer.allocUnsafe(26);\nconst buf2 = Buffer.allocUnsafe(26).fill('!');\n\nfor (let i = 0 ; i < 26 ; i++) {\n // 97 is the decimal ASCII value for 'a'\n buf1[i] = i + 97;\n}\n\nbuf1.copy(buf2, 8, 16, 20);\n\n// Prints: !!!!!!!!qrst!!!!!!!!!!!!!\nconsole.log(buf2.toString('ascii', 0, 25));\n
\nExample: Create a single Buffer
and copy data from one region to an\noverlapping region within the same Buffer
const buf = Buffer.allocUnsafe(26);\n\nfor (let i = 0 ; i < 26 ; i++) {\n // 97 is the decimal ASCII value for 'a'\n buf[i] = i + 97;\n}\n\nbuf.copy(buf, 0, 4, 10);\n\n// Prints: efghijghijklmnopqrstuvwxyz\nconsole.log(buf.toString());\n
\n"
},
{
"textRaw": "buf.entries()",
"type": "method",
"name": "entries",
"meta": {
"added": [
"v1.1.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Iterator} ",
"name": "return",
"type": "Iterator"
},
"params": []
},
{
"params": []
}
],
"desc": "Creates and returns an iterator of [index, byte]
pairs from the contents of\nbuf
.
Example: Log the entire contents of a Buffer
const buf = Buffer.from('buffer');\n\n// Prints:\n// [0, 98]\n// [1, 117]\n// [2, 102]\n// [3, 102]\n// [4, 101]\n// [5, 114]\nfor (const pair of buf.entries()) {\n console.log(pair);\n}\n
\n"
},
{
"textRaw": "buf.equals(otherBuffer)",
"type": "method",
"name": "equals",
"meta": {
"added": [
"v0.11.13"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Boolean} ",
"name": "return",
"type": "Boolean"
},
"params": [
{
"textRaw": "`otherBuffer` {Buffer} A `Buffer` to compare to ",
"name": "otherBuffer",
"type": "Buffer",
"desc": "A `Buffer` to compare to"
}
]
},
{
"params": [
{
"name": "otherBuffer"
}
]
}
],
"desc": "Returns true
if both buf
and otherBuffer
have exactly the same bytes,\nfalse
otherwise.
Examples:
\nconst buf1 = Buffer.from('ABC');\nconst buf2 = Buffer.from('414243', 'hex');\nconst buf3 = Buffer.from('ABCD');\n\n// Prints: true\nconsole.log(buf1.equals(buf2));\n\n// Prints: false\nconsole.log(buf1.equals(buf3));\n
\n"
},
{
"textRaw": "buf.fill(value[, offset[, end]][, encoding])",
"type": "method",
"name": "fill",
"meta": {
"added": [
"v0.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer} A reference to `buf` ",
"name": "return",
"type": "Buffer",
"desc": "A reference to `buf`"
},
"params": [
{
"textRaw": "`value` {String | Buffer | Integer} The value to fill `buf` with ",
"name": "value",
"type": "String | Buffer | Integer",
"desc": "The value to fill `buf` with"
},
{
"textRaw": "`offset` {Integer} Where to start filling `buf`. **Default:** `0` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start filling `buf`. **Default:** `0`",
"optional": true
},
{
"textRaw": "`end` {Integer} Where to stop filling `buf` (not inclusive). **Default:** [`buf.length`] ",
"name": "end",
"type": "Integer",
"desc": "Where to stop filling `buf` (not inclusive). **Default:** [`buf.length`]",
"optional": true
},
{
"textRaw": "`encoding` {String} If `value` is a string, this is its encoding. **Default:** `'utf8'` ",
"name": "encoding",
"type": "String",
"desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset",
"optional": true
},
{
"name": "end",
"optional": true
},
{
"name": "encoding",
"optional": true
}
]
}
],
"desc": "Fills buf
with the specified value
. If the offset
and end
are not given,\nthe entire buf
will be filled. This is meant to be a small simplification to\nallow the creation and filling of a Buffer
to be done on a single line.
Example: Fill a Buffer
with the ASCII character 'h'
const b = Buffer.allocUnsafe(50).fill('h');\n\n// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh\nconsole.log(b.toString());\n
\nvalue
is coerced to a uint32
value if it is not a String or Integer.
If the final write of a fill()
operation falls on a multi-byte character,\nthen only the first bytes of that character that fit into buf
are written.
Example: Fill a Buffer
with a two-byte character
// Prints: <Buffer c8 a2 c8>\nconsole.log(Buffer.allocUnsafe(3).fill('\\u0222'));\n
\n"
},
{
"textRaw": "buf.indexOf(value[, byteOffset][, encoding])",
"type": "method",
"name": "indexOf",
"meta": {
"added": [
"v1.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} The index of the first occurrence of `value` in `buf` or `-1` if `buf` does not contain `value` ",
"name": "return",
"type": "Integer",
"desc": "The index of the first occurrence of `value` in `buf` or `-1` if `buf` does not contain `value`"
},
"params": [
{
"textRaw": "`value` {String | Buffer | Integer} What to search for ",
"name": "value",
"type": "String | Buffer | Integer",
"desc": "What to search for"
},
{
"textRaw": "`byteOffset` {Integer} Where to begin searching in `buf`. **Default:** `0` ",
"name": "byteOffset",
"type": "Integer",
"desc": "Where to begin searching in `buf`. **Default:** `0`",
"optional": true
},
{
"textRaw": "`encoding` {String} If `value` is a string, this is its encoding. **Default:** `'utf8'` ",
"name": "encoding",
"type": "String",
"desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "byteOffset",
"optional": true
},
{
"name": "encoding",
"optional": true
}
]
}
],
"desc": "If value
is:
value
is interpreted according to the character encoding in\nencoding
.Buffer
, value
will be used in its entirety. To compare a partial\nBuffer
use buf.slice()
.value
will be interpreted as an unsigned 8-bit integer\nvalue between 0
and 255
.Examples:
\nconst buf = Buffer.from('this is a buffer');\n\n// Prints: 0\nconsole.log(buf.indexOf('this'));\n\n// Prints: 2\nconsole.log(buf.indexOf('is'));\n\n// Prints: 8\nconsole.log(buf.indexOf(Buffer.from('a buffer')));\n\n// Prints: 8\n// (97 is the decimal ASCII value for 'a')\nconsole.log(buf.indexOf(97));\n\n// Prints: -1\nconsole.log(buf.indexOf(Buffer.from('a buffer example')));\n\n// Prints: 8\nconsole.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8)));\n\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'ucs2');\n\n// Prints: 4\nconsole.log(utf16Buffer.indexOf('\\u03a3', 0, 'ucs2'));\n\n// Prints: 6\nconsole.log(utf16Buffer.indexOf('\\u03a3', -4, 'ucs2'));\n
\nIf value
is not a string, number, or Buffer
, this method will throw a\nTypeError
. If value
is a number, it will be coerced to a valid byte value,\nan integer between 0 and 255.
If byteOffset
is not a number, it will be coerced to a number. Any arguments\nthat coerce to NaN
or 0, like {}
, []
, null
or undefined
, will search\nthe whole buffer. This behavior matches String#indexOf()
.
const b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte\n// Prints: 2, equivalent to searching for 99 or 'c'\nconsole.log(b.indexOf(99.9));\nconsole.log(b.indexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN or 0\n// Prints: 1, searching the whole buffer\nconsole.log(b.indexOf('b', undefined));\nconsole.log(b.indexOf('b', {}));\nconsole.log(b.indexOf('b', null));\nconsole.log(b.indexOf('b', []));\n
\n"
},
{
"textRaw": "buf.includes(value[, byteOffset][, encoding])",
"type": "method",
"name": "includes",
"meta": {
"added": [
"v5.3.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Boolean} `true` if `value` was found in `buf`, `false` otherwise ",
"name": "return",
"type": "Boolean",
"desc": "`true` if `value` was found in `buf`, `false` otherwise"
},
"params": [
{
"textRaw": "`value` {String | Buffer | Integer} What to search for ",
"name": "value",
"type": "String | Buffer | Integer",
"desc": "What to search for"
},
{
"textRaw": "`byteOffset` {Integer} Where to begin searching in `buf`. **Default:** `0` ",
"name": "byteOffset",
"type": "Integer",
"desc": "Where to begin searching in `buf`. **Default:** `0`",
"optional": true
},
{
"textRaw": "`encoding` {String} If `value` is a string, this is its encoding. **Default:** `'utf8'` ",
"name": "encoding",
"type": "String",
"desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "byteOffset",
"optional": true
},
{
"name": "encoding",
"optional": true
}
]
}
],
"desc": "Equivalent to buf.indexOf() !== -1
.
Examples:
\nconst buf = Buffer.from('this is a buffer');\n\n// Prints: true\nconsole.log(buf.includes('this'));\n\n// Prints: true\nconsole.log(buf.includes('is'));\n\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer')));\n\n// Prints: true\n// (97 is the decimal ASCII value for 'a')\nconsole.log(buf.includes(97));\n\n// Prints: false\nconsole.log(buf.includes(Buffer.from('a buffer example')));\n\n// Prints: true\nconsole.log(buf.includes(Buffer.from('a buffer example').slice(0, 8)));\n\n// Prints: false\nconsole.log(buf.includes('this', 4));\n
\n"
},
{
"textRaw": "buf.keys()",
"type": "method",
"name": "keys",
"meta": {
"added": [
"v1.1.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Iterator} ",
"name": "return",
"type": "Iterator"
},
"params": []
},
{
"params": []
}
],
"desc": "Creates and returns an iterator of buf
keys (indices).
Example:
\nconst buf = Buffer.from('buffer');\n\n// Prints:\n// 0\n// 1\n// 2\n// 3\n// 4\n// 5\nfor (const key of buf.keys()) {\n console.log(key);\n}\n
\n"
},
{
"textRaw": "buf.lastIndexOf(value[, byteOffset][, encoding])",
"type": "method",
"name": "lastIndexOf",
"meta": {
"added": [
"v6.0.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} The index of the last occurrence of `value` in `buf` or `-1` if `buf` does not contain `value` ",
"name": "return",
"type": "Integer",
"desc": "The index of the last occurrence of `value` in `buf` or `-1` if `buf` does not contain `value`"
},
"params": [
{
"textRaw": "`value` {String | Buffer | Integer} What to search for ",
"name": "value",
"type": "String | Buffer | Integer",
"desc": "What to search for"
},
{
"textRaw": "`byteOffset` {Integer} Where to begin searching in `buf`. **Default:** [`buf.length`]` - 1` ",
"name": "byteOffset",
"type": "Integer",
"desc": "Where to begin searching in `buf`. **Default:** [`buf.length`]` - 1`",
"optional": true
},
{
"textRaw": "`encoding` {String} If `value` is a string, this is its encoding. **Default:** `'utf8'` ",
"name": "encoding",
"type": "String",
"desc": "If `value` is a string, this is its encoding. **Default:** `'utf8'`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "byteOffset",
"optional": true
},
{
"name": "encoding",
"optional": true
}
]
}
],
"desc": "Identical to buf.indexOf()
, except buf
is searched from back to front\ninstead of front to back.
Examples:
\nconst buf = Buffer.from('this buffer is a buffer');\n\n// Prints: 0\nconsole.log(buf.lastIndexOf('this'));\n\n// Prints: 17\nconsole.log(buf.lastIndexOf('buffer'));\n\n// Prints: 17\nconsole.log(buf.lastIndexOf(Buffer.from('buffer')));\n\n// Prints: 15\n// (97 is the decimal ASCII value for 'a')\nconsole.log(buf.lastIndexOf(97));\n\n// Prints: -1\nconsole.log(buf.lastIndexOf(Buffer.from('yolo')));\n\n// Prints: 5\nconsole.log(buf.lastIndexOf('buffer', 5));\n\n// Prints: -1\nconsole.log(buf.lastIndexOf('buffer', 4));\n\n\nconst utf16Buffer = Buffer.from('\\u039a\\u0391\\u03a3\\u03a3\\u0395', 'ucs2');\n\n// Prints: 6\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', undefined, 'ucs2'));\n\n// Prints: 4\nconsole.log(utf16Buffer.lastIndexOf('\\u03a3', -5, 'ucs2'));\n
\nIf value
is not a string, number, or Buffer
, this method will throw a\nTypeError
. If value
is a number, it will be coerced to a valid byte value,\nan integer between 0 and 255.
If byteOffset
is not a number, it will be coerced to a number. Any arguments\nthat coerce to NaN
, like {}
or undefined
, will search the whole buffer.\nThis behavior matches String#lastIndexOf()
.
const b = Buffer.from('abcdef');\n\n// Passing a value that's a number, but not a valid byte\n// Prints: 2, equivalent to searching for 99 or 'c'\nconsole.log(b.lastIndexOf(99.9));\nconsole.log(b.lastIndexOf(256 + 99));\n\n// Passing a byteOffset that coerces to NaN\n// Prints: 1, searching the whole buffer\nconsole.log(b.lastIndexOf('b', undefined));\nconsole.log(b.lastIndexOf('b', {}));\n\n// Passing a byteOffset that coerces to 0\n// Prints: -1, equivalent to passing 0\nconsole.log(b.lastIndexOf('b', null));\nconsole.log(b.lastIndexOf('b', []));\n
\n"
},
{
"textRaw": "buf.readDoubleBE(offset[, noAssert])",
"type": "method",
"name": "readDoubleBE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Number} ",
"name": "return",
"type": "Number"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 8` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 8`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a 64-bit double from buf
at the specified offset
with specified\nendian format (readDoubleBE()
returns big endian, readDoubleLE()
returns\nlittle endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\n// Prints: 8.20788039913184e-304\nconsole.log(buf.readDoubleBE());\n\n// Prints: 5.447603722011605e-270\nconsole.log(buf.readDoubleLE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readDoubleLE(1));\n\n// Warning: reads passed end of buffer!\n// This will result in a segmentation fault! Don't do this!\nconsole.log(buf.readDoubleLE(1, true));\n
\n"
},
{
"textRaw": "buf.readDoubleLE(offset[, noAssert])",
"type": "method",
"name": "readDoubleLE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Number} ",
"name": "return",
"type": "Number"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 8` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 8`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a 64-bit double from buf
at the specified offset
with specified\nendian format (readDoubleBE()
returns big endian, readDoubleLE()
returns\nlittle endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);\n\n// Prints: 8.20788039913184e-304\nconsole.log(buf.readDoubleBE());\n\n// Prints: 5.447603722011605e-270\nconsole.log(buf.readDoubleLE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readDoubleLE(1));\n\n// Warning: reads passed end of buffer!\n// This will result in a segmentation fault! Don't do this!\nconsole.log(buf.readDoubleLE(1, true));\n
\n"
},
{
"textRaw": "buf.readFloatBE(offset[, noAssert])",
"type": "method",
"name": "readFloatBE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Number} ",
"name": "return",
"type": "Number"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a 32-bit float from buf
at the specified offset
with specified\nendian format (readFloatBE()
returns big endian, readFloatLE()
returns\nlittle endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([1, 2, 3, 4]);\n\n// Prints: 2.387939260590663e-38\nconsole.log(buf.readFloatBE());\n\n// Prints: 1.539989614439558e-36\nconsole.log(buf.readFloatLE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readFloatLE(1));\n\n// Warning: reads passed end of buffer!\n// This will result in a segmentation fault! Don't do this!\nconsole.log(buf.readFloatLE(1, true));\n
\n"
},
{
"textRaw": "buf.readFloatLE(offset[, noAssert])",
"type": "method",
"name": "readFloatLE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Number} ",
"name": "return",
"type": "Number"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a 32-bit float from buf
at the specified offset
with specified\nendian format (readFloatBE()
returns big endian, readFloatLE()
returns\nlittle endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([1, 2, 3, 4]);\n\n// Prints: 2.387939260590663e-38\nconsole.log(buf.readFloatBE());\n\n// Prints: 1.539989614439558e-36\nconsole.log(buf.readFloatLE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readFloatLE(1));\n\n// Warning: reads passed end of buffer!\n// This will result in a segmentation fault! Don't do this!\nconsole.log(buf.readFloatLE(1, true));\n
\n"
},
{
"textRaw": "buf.readInt8(offset[, noAssert])",
"type": "method",
"name": "readInt8",
"meta": {
"added": [
"v0.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 1` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 1`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a signed 8-bit integer from buf
at the specified offset
.
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Integers read from a Buffer
are interpreted as two's complement signed values.
Examples:
\nconst buf = Buffer.from([-1, 5]);\n\n// Prints: -1\nconsole.log(buf.readInt8(0));\n\n// Prints: 5\nconsole.log(buf.readInt8(1));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt8(2));\n
\n"
},
{
"textRaw": "buf.readInt16BE(offset[, noAssert])",
"type": "method",
"name": "readInt16BE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a signed 16-bit integer from buf
at the specified offset
with\nthe specified endian format (readInt16BE()
returns big endian,\nreadInt16LE()
returns little endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Integers read from a Buffer
are interpreted as two's complement signed values.
Examples:
\nconst buf = Buffer.from([0, 5]);\n\n// Prints: 5\nconsole.log(buf.readInt16BE());\n\n// Prints: 1280\nconsole.log(buf.readInt16LE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt16LE(1));\n
\n"
},
{
"textRaw": "buf.readInt16LE(offset[, noAssert])",
"type": "method",
"name": "readInt16LE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a signed 16-bit integer from buf
at the specified offset
with\nthe specified endian format (readInt16BE()
returns big endian,\nreadInt16LE()
returns little endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Integers read from a Buffer
are interpreted as two's complement signed values.
Examples:
\nconst buf = Buffer.from([0, 5]);\n\n// Prints: 5\nconsole.log(buf.readInt16BE());\n\n// Prints: 1280\nconsole.log(buf.readInt16LE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt16LE(1));\n
\n"
},
{
"textRaw": "buf.readInt32BE(offset[, noAssert])",
"type": "method",
"name": "readInt32BE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a signed 32-bit integer from buf
at the specified offset
with\nthe specified endian format (readInt32BE()
returns big endian,\nreadInt32LE()
returns little endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Integers read from a Buffer
are interpreted as two's complement signed values.
Examples:
\nconst buf = Buffer.from([0, 0, 0, 5]);\n\n// Prints: 5\nconsole.log(buf.readInt32BE());\n\n// Prints: 83886080\nconsole.log(buf.readInt32LE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt32LE(1));\n
\n"
},
{
"textRaw": "buf.readInt32LE(offset[, noAssert])",
"type": "method",
"name": "readInt32LE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads a signed 32-bit integer from buf
at the specified offset
with\nthe specified endian format (readInt32BE()
returns big endian,\nreadInt32LE()
returns little endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Integers read from a Buffer
are interpreted as two's complement signed values.
Examples:
\nconst buf = Buffer.from([0, 0, 0, 5]);\n\n// Prints: 5\nconsole.log(buf.readInt32BE());\n\n// Prints: 83886080\nconsole.log(buf.readInt32LE());\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readInt32LE(1));\n
\n"
},
{
"textRaw": "buf.readIntBE(offset, byteLength[, noAssert])",
"type": "method",
"name": "readIntBE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength`"
},
{
"textRaw": "`byteLength` {Integer} How many bytes to read. Must satisfy: `0 < byteLength <= 6` ",
"name": "byteLength",
"type": "Integer",
"desc": "How many bytes to read. Must satisfy: `0 < byteLength <= 6`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` and `byteLength` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` and `byteLength` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads byteLength
number of bytes from buf
at the specified offset
\nand interprets the result as a two's complement signed value. Supports up to 48\nbits of accuracy.
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\n// Prints: -546f87a9cbee\nconsole.log(buf.readIntLE(0, 6).toString(16));\n\n// Prints: 1234567890ab\nconsole.log(buf.readIntBE(0, 6).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readIntBE(1, 6).toString(16));\n
\n"
},
{
"textRaw": "buf.readIntLE(offset, byteLength[, noAssert])",
"type": "method",
"name": "readIntLE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength`"
},
{
"textRaw": "`byteLength` {Integer} How many bytes to read. Must satisfy: `0 < byteLength <= 6` ",
"name": "byteLength",
"type": "Integer",
"desc": "How many bytes to read. Must satisfy: `0 < byteLength <= 6`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` and `byteLength` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` and `byteLength` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads byteLength
number of bytes from buf
at the specified offset
\nand interprets the result as a two's complement signed value. Supports up to 48\nbits of accuracy.
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\n// Prints: -546f87a9cbee\nconsole.log(buf.readIntLE(0, 6).toString(16));\n\n// Prints: 1234567890ab\nconsole.log(buf.readIntBE(0, 6).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readIntBE(1, 6).toString(16));\n
\n"
},
{
"textRaw": "buf.readUInt8(offset[, noAssert])",
"type": "method",
"name": "readUInt8",
"meta": {
"added": [
"v0.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 1` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 1`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads an unsigned 8-bit integer from buf
at the specified offset
.
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([1, -2]);\n\n// Prints: 1\nconsole.log(buf.readUInt8(0));\n\n// Prints: 254\nconsole.log(buf.readUInt8(1));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt8(2));\n
\n"
},
{
"textRaw": "buf.readUInt16BE(offset[, noAssert])",
"type": "method",
"name": "readUInt16BE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads an unsigned 16-bit integer from buf
at the specified offset
with\nspecified endian format (readUInt16BE()
returns big endian, readUInt16LE()
\nreturns little endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([0x12, 0x34, 0x56]);\n\n// Prints: 1234\nconsole.log(buf.readUInt16BE(0).toString(16));\n\n// Prints: 3412\nconsole.log(buf.readUInt16LE(0).toString(16));\n\n// Prints: 3456\nconsole.log(buf.readUInt16BE(1).toString(16));\n\n// Prints: 5634\nconsole.log(buf.readUInt16LE(1).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt16LE(2).toString(16));\n
\n"
},
{
"textRaw": "buf.readUInt16LE(offset[, noAssert])",
"type": "method",
"name": "readUInt16LE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 2`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads an unsigned 16-bit integer from buf
at the specified offset
with\nspecified endian format (readUInt16BE()
returns big endian, readUInt16LE()
\nreturns little endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([0x12, 0x34, 0x56]);\n\n// Prints: 1234\nconsole.log(buf.readUInt16BE(0).toString(16));\n\n// Prints: 3412\nconsole.log(buf.readUInt16LE(0).toString(16));\n\n// Prints: 3456\nconsole.log(buf.readUInt16BE(1).toString(16));\n\n// Prints: 5634\nconsole.log(buf.readUInt16LE(1).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt16LE(2).toString(16));\n
\n"
},
{
"textRaw": "buf.readUInt32BE(offset[, noAssert])",
"type": "method",
"name": "readUInt32BE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads an unsigned 32-bit integer from buf
at the specified offset
with\nspecified endian format (readUInt32BE()
returns big endian,\nreadUInt32LE()
returns little endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\n// Prints: 12345678\nconsole.log(buf.readUInt32BE(0).toString(16));\n\n// Prints: 78563412\nconsole.log(buf.readUInt32LE(0).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt32LE(1).toString(16));\n
\n"
},
{
"textRaw": "buf.readUInt32LE(offset[, noAssert])",
"type": "method",
"name": "readUInt32LE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads an unsigned 32-bit integer from buf
at the specified offset
with\nspecified endian format (readUInt32BE()
returns big endian,\nreadUInt32LE()
returns little endian).
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78]);\n\n// Prints: 12345678\nconsole.log(buf.readUInt32BE(0).toString(16));\n\n// Prints: 78563412\nconsole.log(buf.readUInt32LE(0).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUInt32LE(1).toString(16));\n
\n"
},
{
"textRaw": "buf.readUIntBE(offset, byteLength[, noAssert])",
"type": "method",
"name": "readUIntBE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength`"
},
{
"textRaw": "`byteLength` {Integer} How many bytes to read. Must satisfy: `0 < byteLength <= 6` ",
"name": "byteLength",
"type": "Integer",
"desc": "How many bytes to read. Must satisfy: `0 < byteLength <= 6`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` and `byteLength` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` and `byteLength` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads byteLength
number of bytes from buf
at the specified offset
\nand interprets the result as an unsigned integer. Supports up to 48\nbits of accuracy.
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\n// Prints: 1234567890ab\nconsole.log(buf.readUIntBE(0, 6).toString(16));\n\n// Prints: ab9078563412\nconsole.log(buf.readUIntLE(0, 6).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUIntBE(1, 6).toString(16));\n
\n"
},
{
"textRaw": "buf.readUIntLE(offset, byteLength[, noAssert])",
"type": "method",
"name": "readUIntLE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} ",
"name": "return",
"type": "Integer"
},
"params": [
{
"textRaw": "`offset` {Integer} Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start reading. Must satisfy: `0 <= offset <= buf.length - byteLength`"
},
{
"textRaw": "`byteLength` {Integer} How many bytes to read. Must satisfy: `0 < byteLength <= 6` ",
"name": "byteLength",
"type": "Integer",
"desc": "How many bytes to read. Must satisfy: `0 < byteLength <= 6`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `offset` and `byteLength` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `offset` and `byteLength` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Reads byteLength
number of bytes from buf
at the specified offset
\nand interprets the result as an unsigned integer. Supports up to 48\nbits of accuracy.
Setting noAssert
to true
allows offset
to be beyond the end of buf
, but\nthe result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]);\n\n// Prints: 1234567890ab\nconsole.log(buf.readUIntBE(0, 6).toString(16));\n\n// Prints: ab9078563412\nconsole.log(buf.readUIntLE(0, 6).toString(16));\n\n// Throws an exception: RangeError: Index out of range\nconsole.log(buf.readUIntBE(1, 6).toString(16));\n
\n"
},
{
"textRaw": "buf.slice([start[, end]])",
"type": "method",
"name": "slice",
"meta": {
"added": [
"v0.3.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer} ",
"name": "return",
"type": "Buffer"
},
"params": [
{
"textRaw": "`start` {Integer} Where the new `Buffer` will start. **Default:** `0` ",
"name": "start",
"type": "Integer",
"desc": "Where the new `Buffer` will start. **Default:** `0`",
"optional": true
},
{
"textRaw": "`end` {Integer} Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`] ",
"name": "end",
"type": "Integer",
"desc": "Where the new `Buffer` will end (not inclusive). **Default:** [`buf.length`]",
"optional": true
}
]
},
{
"params": [
{
"name": "start",
"optional": true
},
{
"name": "end",
"optional": true
}
]
}
],
"desc": "Returns a new Buffer
that references the same memory as the original, but\noffset and cropped by the start
and end
indices.
Note that modifying the new Buffer
slice will modify the memory in the\noriginal Buffer
because the allocated memory of the two objects overlap.
Example: Create a Buffer
with the ASCII alphabet, take a slice, and then modify\none byte from the original Buffer
const buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0 ; i < 26 ; i++) {\n // 97 is the decimal ASCII value for 'a'\n buf1[i] = i + 97;\n}\n\nconst buf2 = buf1.slice(0, 3);\n\n// Prints: abc\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n\nbuf1[0] = 33;\n\n// Prints: !bc\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n
\nSpecifying negative indexes causes the slice to be generated relative to the\nend of buf
rather than the beginning.
Examples:
\nconst buf = Buffer.from('buffer');\n\n// Prints: buffe\n// (Equivalent to buf.slice(0, 5))\nconsole.log(buf.slice(-6, -1).toString());\n\n// Prints: buff\n// (Equivalent to buf.slice(0, 4))\nconsole.log(buf.slice(-6, -2).toString());\n\n// Prints: uff\n// (Equivalent to buf.slice(1, 4))\nconsole.log(buf.slice(-5, -2).toString());\n
\n"
},
{
"textRaw": "buf.swap16()",
"type": "method",
"name": "swap16",
"meta": {
"added": [
"v5.10.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer} A reference to `buf` ",
"name": "return",
"type": "Buffer",
"desc": "A reference to `buf`"
},
"params": []
},
{
"params": []
}
],
"desc": "Interprets buf
as an array of unsigned 16-bit integers and swaps the byte-order\nin-place. Throws a RangeError
if buf.length
is not a multiple of 2.
Examples:
\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\nconsole.log(buf1);\n\nbuf1.swap16();\n\n// Prints: <Buffer 02 01 04 03 06 05 08 07>\nconsole.log(buf1);\n\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\n// Throws an exception: RangeError: Buffer size must be a multiple of 16-bits\nbuf2.swap16();\n
\n"
},
{
"textRaw": "buf.swap32()",
"type": "method",
"name": "swap32",
"meta": {
"added": [
"v5.10.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer} A reference to `buf` ",
"name": "return",
"type": "Buffer",
"desc": "A reference to `buf`"
},
"params": []
},
{
"params": []
}
],
"desc": "Interprets buf
as an array of unsigned 32-bit integers and swaps the byte-order\nin-place. Throws a RangeError
if buf.length
is not a multiple of 4.
Examples:
\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\nconsole.log(buf1);\n\nbuf1.swap32();\n\n// Prints: <Buffer 04 03 02 01 08 07 06 05>\nconsole.log(buf1);\n\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\n// Throws an exception: RangeError: Buffer size must be a multiple of 32-bits\nbuf2.swap32();\n
\n"
},
{
"textRaw": "buf.swap64()",
"type": "method",
"name": "swap64",
"meta": {
"added": [
"v6.3.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer} A reference to `buf` ",
"name": "return",
"type": "Buffer",
"desc": "A reference to `buf`"
},
"params": []
},
{
"params": []
}
],
"desc": "Interprets buf
as an array of 64-bit numbers and swaps the byte-order in-place.\nThrows a RangeError
if buf.length
is not a multiple of 8.
Examples:
\nconst buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);\n\n// Prints: <Buffer 01 02 03 04 05 06 07 08>\nconsole.log(buf1);\n\nbuf1.swap64();\n\n// Prints: <Buffer 08 07 06 05 04 03 02 01>\nconsole.log(buf1);\n\n\nconst buf2 = Buffer.from([0x1, 0x2, 0x3]);\n\n// Throws an exception: RangeError: Buffer size must be a multiple of 64-bits\nbuf2.swap64();\n
\nNote that JavaScript cannot encode 64-bit integers. This method is intended\nfor working with 64-bit floats.
\n" }, { "textRaw": "buf.toString([encoding[, start[, end]]])", "type": "method", "name": "toString", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "return": { "textRaw": "Returns: {String} ", "name": "return", "type": "String" }, "params": [ { "textRaw": "`encoding` {String} The character encoding to decode to. **Default:** `'utf8'` ", "name": "encoding", "type": "String", "desc": "The character encoding to decode to. **Default:** `'utf8'`", "optional": true }, { "textRaw": "`start` {Integer} The byte offset to start decoding at. **Default:** `0` ", "name": "start", "type": "Integer", "desc": "The byte offset to start decoding at. **Default:** `0`", "optional": true }, { "textRaw": "`end` {Integer} The byte offset to stop decoding at (not inclusive). **Default:** [`buf.length`] ", "name": "end", "type": "Integer", "desc": "The byte offset to stop decoding at (not inclusive). **Default:** [`buf.length`]", "optional": true } ] }, { "params": [ { "name": "encoding", "optional": true }, { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "Decodes buf
to a string according to the specified character encoding in\nencoding
. start
and end
may be passed to decode only a subset of buf
.
Examples:
\nconst buf1 = Buffer.allocUnsafe(26);\n\nfor (let i = 0 ; i < 26 ; i++) {\n // 97 is the decimal ASCII value for 'a'\n buf1[i] = i + 97;\n}\n\n// Prints: abcdefghijklmnopqrstuvwxyz\nconsole.log(buf1.toString('ascii'));\n\n// Prints: abcde\nconsole.log(buf1.toString('ascii', 0, 5));\n\n\nconst buf2 = Buffer.from('tést');\n\n// Prints: 74c3a97374\nconsole.log(buf2.toString('hex'));\n\n// Prints: té\nconsole.log(buf2.toString('utf8', 0, 3));\n\n// Prints: té\nconsole.log(buf2.toString(undefined, 0, 3));\n
\n"
},
{
"textRaw": "buf.toJSON()",
"type": "method",
"name": "toJSON",
"meta": {
"added": [
"v0.9.2"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Object} ",
"name": "return",
"type": "Object"
},
"params": []
},
{
"params": []
}
],
"desc": "Returns a JSON representation of buf
. JSON.stringify()
implicitly calls\nthis function when stringifying a Buffer
instance.
Example:
\nconst buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);\nconst json = JSON.stringify(buf);\n\n// Prints: {"type":"Buffer","data":[1,2,3,4,5]}\nconsole.log(json);\n\nconst copy = JSON.parse(json, (key, value) => {\n return value && value.type === 'Buffer'\n ? Buffer.from(value.data)\n : value;\n});\n\n// Prints: <Buffer 01 02 03 04 05>\nconsole.log(copy);\n
\n"
},
{
"textRaw": "buf.values()",
"type": "method",
"name": "values",
"meta": {
"added": [
"v1.1.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Iterator} ",
"name": "return",
"type": "Iterator"
},
"params": []
},
{
"params": []
}
],
"desc": "Creates and returns an iterator for buf
values (bytes). This function is\ncalled automatically when a Buffer
is used in a for..of
statement.
Examples:
\nconst buf = Buffer.from('buffer');\n\n// Prints:\n// 98\n// 117\n// 102\n// 102\n// 101\n// 114\nfor (const value of buf.values()) {\n console.log(value);\n}\n\n// Prints:\n// 98\n// 117\n// 102\n// 102\n// 101\n// 114\nfor (const value of buf) {\n console.log(value);\n}\n
\n"
},
{
"textRaw": "buf.write(string[, offset[, length]][, encoding])",
"type": "method",
"name": "write",
"meta": {
"added": [
"v0.1.90"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} Number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "Number of bytes written"
},
"params": [
{
"textRaw": "`string` {String} String to be written to `buf` ",
"name": "string",
"type": "String",
"desc": "String to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing `string`. **Default:** `0` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing `string`. **Default:** `0`",
"optional": true
},
{
"textRaw": "`length` {Integer} How many bytes to write. **Default:** `buf.length - offset` ",
"name": "length",
"type": "Integer",
"desc": "How many bytes to write. **Default:** `buf.length - offset`",
"optional": true
},
{
"textRaw": "`encoding` {String} The character encoding of `string`. **Default:** `'utf8'` ",
"name": "encoding",
"type": "String",
"desc": "The character encoding of `string`. **Default:** `'utf8'`",
"optional": true
}
]
},
{
"params": [
{
"name": "string"
},
{
"name": "offset",
"optional": true
},
{
"name": "length",
"optional": true
},
{
"name": "encoding",
"optional": true
}
]
}
],
"desc": "Writes string
to buf
at offset
according to the character encoding in encoding
.\nThe length
parameter is the number of bytes to write. If buf
did not contain\nenough space to fit the entire string, only a partial amount of string
will\nbe written. However, partially encoded characters will not be written.
Example:
\nconst buf = Buffer.allocUnsafe(256);\n\nconst len = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\n\n// Prints: 12 bytes: ½ + ¼ = ¾\nconsole.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);\n
\n"
},
{
"textRaw": "buf.writeDoubleBE(value, offset[, noAssert])",
"type": "method",
"name": "writeDoubleBE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Number} Number to be written to `buf` ",
"name": "value",
"type": "Number",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 8` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 8`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeDoubleBE()
writes big endian, writeDoubleLE()
writes little\nendian). value
should be a valid 64-bit double. Behavior is undefined when\nvalue
is anything other than a 64-bit double.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\n// Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\n// Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeDoubleLE(value, offset[, noAssert])",
"type": "method",
"name": "writeDoubleLE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Number} Number to be written to `buf` ",
"name": "value",
"type": "Number",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 8` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 8`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeDoubleBE()
writes big endian, writeDoubleLE()
writes little\nendian). value
should be a valid 64-bit double. Behavior is undefined when\nvalue
is anything other than a 64-bit double.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\n// Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\n// Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeFloatBE(value, offset[, noAssert])",
"type": "method",
"name": "writeFloatBE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Number} Number to be written to `buf` ",
"name": "value",
"type": "Number",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeFloatBE()
writes big endian, writeFloatLE()
writes little\nendian). value
should be a valid 32-bit float. Behavior is undefined when\nvalue
is anything other than a 32-bit float.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\n// Prints: <Buffer 4f 4a fe bb>\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\n// Prints: <Buffer bb fe 4a 4f>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeFloatLE(value, offset[, noAssert])",
"type": "method",
"name": "writeFloatLE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Number} Number to be written to `buf` ",
"name": "value",
"type": "Number",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeFloatBE()
writes big endian, writeFloatLE()
writes little\nendian). value
should be a valid 32-bit float. Behavior is undefined when\nvalue
is anything other than a 32-bit float.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeFloatBE(0xcafebabe, 0);\n\n// Prints: <Buffer 4f 4a fe bb>\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\n// Prints: <Buffer bb fe 4a 4f>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeInt8(value, offset[, noAssert])",
"type": "method",
"name": "writeInt8",
"meta": {
"added": [
"v0.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 1` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 1`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
. value
should be a valid\nsigned 8-bit integer. Behavior is undefined when value
is anything other than\na signed 8-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
value
is interpreted and written as a two's complement signed integer.
Examples:
\nconst buf = Buffer.allocUnsafe(2);\n\nbuf.writeInt8(2, 0);\nbuf.writeInt8(-2, 1);\n\n// Prints: <Buffer 02 fe>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeInt16BE(value, offset[, noAssert])",
"type": "method",
"name": "writeInt16BE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeInt16BE()
writes big endian, writeInt16LE()
writes little\nendian). value
should be a valid signed 16-bit integer. Behavior is undefined\nwhen value
is anything other than a signed 16-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
value
is interpreted and written as a two's complement signed integer.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt16BE(0x0102, 0);\nbuf.writeInt16LE(0x0304, 2);\n\n// Prints: <Buffer 01 02 04 03>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeInt16LE(value, offset[, noAssert])",
"type": "method",
"name": "writeInt16LE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeInt16BE()
writes big endian, writeInt16LE()
writes little\nendian). value
should be a valid signed 16-bit integer. Behavior is undefined\nwhen value
is anything other than a signed 16-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
value
is interpreted and written as a two's complement signed integer.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeInt16BE(0x0102, 0);\nbuf.writeInt16LE(0x0304, 2);\n\n// Prints: <Buffer 01 02 04 03>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeInt32BE(value, offset[, noAssert])",
"type": "method",
"name": "writeInt32BE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeInt32BE()
writes big endian, writeInt32LE()
writes little\nendian). value
should be a valid signed 32-bit integer. Behavior is undefined\nwhen value
is anything other than a signed 32-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
value
is interpreted and written as a two's complement signed integer.
Examples:
\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeInt32BE(0x01020304, 0);\nbuf.writeInt32LE(0x05060708, 4);\n\n// Prints: <Buffer 01 02 03 04 08 07 06 05>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeInt32LE(value, offset[, noAssert])",
"type": "method",
"name": "writeInt32LE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeInt32BE()
writes big endian, writeInt32LE()
writes little\nendian). value
should be a valid signed 32-bit integer. Behavior is undefined\nwhen value
is anything other than a signed 32-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
value
is interpreted and written as a two's complement signed integer.
Examples:
\nconst buf = Buffer.allocUnsafe(8);\n\nbuf.writeInt32BE(0x01020304, 0);\nbuf.writeInt32LE(0x05060708, 4);\n\n// Prints: <Buffer 01 02 03 04 08 07 06 05>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeIntBE(value, offset, byteLength[, noAssert])",
"type": "method",
"name": "writeIntBE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength`"
},
{
"textRaw": "`byteLength` {Integer} How many bytes to write. Must satisfy: `0 < byteLength <= 6` ",
"name": "byteLength",
"type": "Integer",
"desc": "How many bytes to write. Must satisfy: `0 < byteLength <= 6`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value`, `offset`, and `byteLength` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value`, `offset`, and `byteLength` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes byteLength
bytes of value
to buf
at the specified offset
.\nSupports up to 48 bits of accuracy. Behavior is undefined when value
is\nanything other than a signed integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer 12 34 56 78 90 ab>\nconsole.log(buf);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer ab 90 78 56 34 12>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeIntLE(value, offset, byteLength[, noAssert])",
"type": "method",
"name": "writeIntLE",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength`"
},
{
"textRaw": "`byteLength` {Integer} How many bytes to write. Must satisfy: `0 < byteLength <= 6` ",
"name": "byteLength",
"type": "Integer",
"desc": "How many bytes to write. Must satisfy: `0 < byteLength <= 6`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value`, `offset`, and `byteLength` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value`, `offset`, and `byteLength` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes byteLength
bytes of value
to buf
at the specified offset
.\nSupports up to 48 bits of accuracy. Behavior is undefined when value
is\nanything other than a signed integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer 12 34 56 78 90 ab>\nconsole.log(buf);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer ab 90 78 56 34 12>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeUInt8(value, offset[, noAssert])",
"type": "method",
"name": "writeUInt8",
"meta": {
"added": [
"v0.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 1` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 1`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
. value
should be a\nvalid unsigned 8-bit integer. Behavior is undefined when value
is anything\nother than an unsigned 8-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\n// Prints: <Buffer 03 04 23 42>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeUInt16BE(value, offset[, noAssert])",
"type": "method",
"name": "writeUInt16BE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeUInt16BE()
writes big endian, writeUInt16LE()
writes little\nendian). value
should be a valid unsigned 16-bit integer. Behavior is\nundefined when value
is anything other than an unsigned 16-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\n// Prints: <Buffer de ad be ef>\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\n// Prints: <Buffer ad de ef be>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeUInt16LE(value, offset[, noAssert])",
"type": "method",
"name": "writeUInt16LE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 2`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeUInt16BE()
writes big endian, writeUInt16LE()
writes little\nendian). value
should be a valid unsigned 16-bit integer. Behavior is\nundefined when value
is anything other than an unsigned 16-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\n// Prints: <Buffer de ad be ef>\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\n// Prints: <Buffer ad de ef be>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeUInt32BE(value, offset[, noAssert])",
"type": "method",
"name": "writeUInt32BE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeUInt32BE()
writes big endian, writeUInt32LE()
writes little\nendian). value
should be a valid unsigned 32-bit integer. Behavior is\nundefined when value
is anything other than an unsigned 32-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\n// Prints: <Buffer fe ed fa ce>\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\n// Prints: <Buffer ce fa ed fe>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeUInt32LE(value, offset[, noAssert])",
"type": "method",
"name": "writeUInt32LE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - 4`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value` and `offset` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value` and `offset` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes value
to buf
at the specified offset
with specified endian\nformat (writeUInt32BE()
writes big endian, writeUInt32LE()
writes little\nendian). value
should be a valid unsigned 32-bit integer. Behavior is\nundefined when value
is anything other than an unsigned 32-bit integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(4);\n\nbuf.writeUInt32BE(0xfeedface, 0);\n\n// Prints: <Buffer fe ed fa ce>\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\n// Prints: <Buffer ce fa ed fe>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeUIntBE(value, offset, byteLength[, noAssert])",
"type": "method",
"name": "writeUIntBE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength`"
},
{
"textRaw": "`byteLength` {Integer} How many bytes to write. Must satisfy: `0 < byteLength <= 6` ",
"name": "byteLength",
"type": "Integer",
"desc": "How many bytes to write. Must satisfy: `0 < byteLength <= 6`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value`, `offset`, and `byteLength` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value`, `offset`, and `byteLength` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes byteLength
bytes of value
to buf
at the specified offset
.\nSupports up to 48 bits of accuracy. Behavior is undefined when value
is\nanything other than an unsigned integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer 12 34 56 78 90 ab>\nconsole.log(buf);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer ab 90 78 56 34 12>\nconsole.log(buf);\n
\n"
},
{
"textRaw": "buf.writeUIntLE(value, offset, byteLength[, noAssert])",
"type": "method",
"name": "writeUIntLE",
"meta": {
"added": [
"v0.5.5"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Integer} `offset` plus the number of bytes written ",
"name": "return",
"type": "Integer",
"desc": "`offset` plus the number of bytes written"
},
"params": [
{
"textRaw": "`value` {Integer} Number to be written to `buf` ",
"name": "value",
"type": "Integer",
"desc": "Number to be written to `buf`"
},
{
"textRaw": "`offset` {Integer} Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength` ",
"name": "offset",
"type": "Integer",
"desc": "Where to start writing. Must satisfy: `0 <= offset <= buf.length - byteLength`"
},
{
"textRaw": "`byteLength` {Integer} How many bytes to write. Must satisfy: `0 < byteLength <= 6` ",
"name": "byteLength",
"type": "Integer",
"desc": "How many bytes to write. Must satisfy: `0 < byteLength <= 6`"
},
{
"textRaw": "`noAssert` {Boolean} Skip `value`, `offset`, and `byteLength` validation? **Default:** `false` ",
"name": "noAssert",
"type": "Boolean",
"desc": "Skip `value`, `offset`, and `byteLength` validation? **Default:** `false`",
"optional": true
}
]
},
{
"params": [
{
"name": "value"
},
{
"name": "offset"
},
{
"name": "byteLength"
},
{
"name": "noAssert",
"optional": true
}
]
}
],
"desc": "Writes byteLength
bytes of value
to buf
at the specified offset
.\nSupports up to 48 bits of accuracy. Behavior is undefined when value
is\nanything other than an unsigned integer.
Setting noAssert
to true
allows the encoded form of value
to extend beyond\nthe end of buf
, but the result should be considered undefined behavior.
Examples:
\nconst buf = Buffer.allocUnsafe(6);\n\nbuf.writeUIntBE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer 12 34 56 78 90 ab>\nconsole.log(buf);\n\nbuf.writeUIntLE(0x1234567890ab, 0, 6);\n\n// Prints: <Buffer ab 90 78 56 34 12>\nconsole.log(buf);\n
\n"
}
],
"signatures": [
{
"params": [
{
"textRaw": "`array` {Array} An array of bytes to copy from ",
"name": "array",
"type": "Array",
"desc": "An array of bytes to copy from"
}
],
"desc": "Allocates a new Buffer
using an array
of octets.
Example:
\n// Creates a new Buffer containing the ASCII bytes of the string 'buffer'\nconst buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n
\n"
},
{
"params": [
{
"name": "array"
}
],
"desc": "Allocates a new Buffer
using an array
of octets.
Example:
\n// Creates a new Buffer containing the ASCII bytes of the string 'buffer'\nconst buf = new Buffer([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);\n
\n"
},
{
"params": [
{
"textRaw": "`buffer` {Buffer} An existing `Buffer` to copy data from ",
"name": "buffer",
"type": "Buffer",
"desc": "An existing `Buffer` to copy data from"
}
],
"desc": "Copies the passed buffer
data onto a new Buffer
instance.
Example:
\nconst buf1 = new Buffer('buffer');\nconst buf2 = new Buffer(buf1);\n\nbuf1[0] = 0x61;\n\n// Prints: auffer\nconsole.log(buf1.toString());\n\n// Prints: buffer\nconsole.log(buf2.toString());\n
\n"
},
{
"params": [
{
"name": "buffer"
}
],
"desc": "Copies the passed buffer
data onto a new Buffer
instance.
Example:
\nconst buf1 = new Buffer('buffer');\nconst buf2 = new Buffer(buf1);\n\nbuf1[0] = 0x61;\n\n// Prints: auffer\nconsole.log(buf1.toString());\n\n// Prints: buffer\nconsole.log(buf2.toString());\n
\n"
},
{
"params": [
{
"textRaw": "`arrayBuffer` {ArrayBuffer} An [`ArrayBuffer`] or the `.buffer` property of a [`TypedArray`]. ",
"name": "arrayBuffer",
"type": "ArrayBuffer",
"desc": "An [`ArrayBuffer`] or the `.buffer` property of a [`TypedArray`]."
},
{
"textRaw": "`byteOffset` {Integer} Index of first byte to expose. **Default:** `0` ",
"name": "byteOffset",
"type": "Integer",
"desc": "Index of first byte to expose. **Default:** `0`",
"optional": true
},
{
"textRaw": "`length` {Integer} Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset` ",
"name": "length",
"type": "Integer",
"desc": "Number of bytes to expose. **Default:** `arrayBuffer.length - byteOffset`",
"optional": true
}
],
"desc": "Stability: 0 - Deprecated: Use\nBuffer.from(arrayBuffer[, byteOffset [, length]])
\ninstead.
This creates a view of the ArrayBuffer
without copying the underlying\nmemory. For example, when passed a reference to the .buffer
property of a\nTypedArray
instance, the newly created Buffer
will share the same\nallocated memory as the TypedArray
.
The optional byteOffset
and length
arguments specify a memory range within\nthe arrayBuffer
that will be shared by the Buffer
.
Example:
\nconst arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`\nconst buf = new Buffer(arr.buffer);\n\n// Prints: <Buffer 88 13 a0 0f>\nconsole.log(buf);\n\n// Changing the original Uint16Array changes the Buffer also\narr[1] = 6000;\n\n// Prints: <Buffer 88 13 70 17>\nconsole.log(buf);\n
\n"
},
{
"params": [
{
"name": "arrayBuffer"
},
{
"name": "byteOffset",
"optional": true
},
{
"name": "length",
"optional": true
}
],
"desc": "Stability: 0 - Deprecated: Use\nBuffer.from(arrayBuffer[, byteOffset [, length]])
\ninstead.
This creates a view of the ArrayBuffer
without copying the underlying\nmemory. For example, when passed a reference to the .buffer
property of a\nTypedArray
instance, the newly created Buffer
will share the same\nallocated memory as the TypedArray
.
The optional byteOffset
and length
arguments specify a memory range within\nthe arrayBuffer
that will be shared by the Buffer
.
Example:
\nconst arr = new Uint16Array(2);\n\narr[0] = 5000;\narr[1] = 4000;\n\n// Shares memory with `arr`\nconst buf = new Buffer(arr.buffer);\n\n// Prints: <Buffer 88 13 a0 0f>\nconsole.log(buf);\n\n// Changing the original Uint16Array changes the Buffer also\narr[1] = 6000;\n\n// Prints: <Buffer 88 13 70 17>\nconsole.log(buf);\n
\n"
},
{
"params": [
{
"textRaw": "`size` {Integer} The desired length of the new `Buffer` ",
"name": "size",
"type": "Integer",
"desc": "The desired length of the new `Buffer`"
}
],
"desc": "Stability: 0 - Deprecated: Use Buffer.alloc()
instead (also see\nBuffer.allocUnsafe()
).
Allocates a new Buffer
of size
bytes. If the size
is larger than\nbuffer.kMaxLength
or smaller than 0, a RangeError
will be thrown.\nA zero-length Buffer
will be created if size
is 0.
Unlike ArrayBuffers
, the underlying memory for Buffer
instances\ncreated in this way is not initialized. The contents of a newly created Buffer
\nare unknown and could contain sensitive data. Use\nBuffer.alloc(size)
instead to initialize a Buffer
to zeroes.
Example:
\nconst buf = new Buffer(10);\n\n// Prints: (contents may vary): <Buffer 48 21 4b 00 00 00 00 00 30 dd>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\nconsole.log(buf);\n
\n"
},
{
"params": [
{
"name": "size"
}
],
"desc": "Stability: 0 - Deprecated: Use Buffer.alloc()
instead (also see\nBuffer.allocUnsafe()
).
Allocates a new Buffer
of size
bytes. If the size
is larger than\nbuffer.kMaxLength
or smaller than 0, a RangeError
will be thrown.\nA zero-length Buffer
will be created if size
is 0.
Unlike ArrayBuffers
, the underlying memory for Buffer
instances\ncreated in this way is not initialized. The contents of a newly created Buffer
\nare unknown and could contain sensitive data. Use\nBuffer.alloc(size)
instead to initialize a Buffer
to zeroes.
Example:
\nconst buf = new Buffer(10);\n\n// Prints: (contents may vary): <Buffer 48 21 4b 00 00 00 00 00 30 dd>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>\nconsole.log(buf);\n
\n"
},
{
"params": [
{
"textRaw": "`string` {String} String to encode ",
"name": "string",
"type": "String",
"desc": "String to encode"
},
{
"textRaw": "`encoding` {String} The encoding of `string`. **Default:** `'utf8'` ",
"name": "encoding",
"type": "String",
"desc": "The encoding of `string`. **Default:** `'utf8'`",
"optional": true
}
],
"desc": "Stability: 0 - Deprecated:\nUse Buffer.from(string[, encoding])
instead.
Creates a new Buffer
containing the given JavaScript string string
. If\nprovided, the encoding
parameter identifies the character encoding of string
.
Examples:
\nconst buf1 = new Buffer('this is a tést');\n\n// Prints: this is a tést\nconsole.log(buf1.toString());\n\n// Prints: this is a tC)st\nconsole.log(buf1.toString('ascii'));\n\n\nconst buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');\n\n// Prints: this is a tést\nconsole.log(buf2.toString());\n
\n"
},
{
"params": [
{
"name": "string"
},
{
"name": "encoding",
"optional": true
}
],
"desc": "Stability: 0 - Deprecated:\nUse Buffer.from(string[, encoding])
instead.
Creates a new Buffer
containing the given JavaScript string string
. If\nprovided, the encoding
parameter identifies the character encoding of string
.
Examples:
\nconst buf1 = new Buffer('this is a tést');\n\n// Prints: this is a tést\nconsole.log(buf1.toString());\n\n// Prints: this is a tC)st\nconsole.log(buf1.toString('ascii'));\n\n\nconst buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');\n\n// Prints: this is a tést\nconsole.log(buf2.toString());\n
\n"
}
]
},
{
"textRaw": "Class: SlowBuffer",
"type": "class",
"name": "SlowBuffer",
"meta": {
"deprecated": [
"v6.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated: Use [`Buffer.allocUnsafeSlow()`] instead.",
"desc": "Returns an un-pooled Buffer
.
In order to avoid the garbage collection overhead of creating many individually\nallocated Buffer
instances, by default allocations under 4KB are sliced from a\nsingle larger allocated object. This approach improves both performance and memory\nusage since v8 does not need to track and cleanup as many Persistent
objects.
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.
Example:
\n// Need to keep around a few small chunks of memory\nconst store = [];\n\nsocket.on('readable', () => {\n const data = socket.read();\n\n // Allocate for retained data\n const sb = SlowBuffer(10);\n\n // Copy the data into the new allocation\n data.copy(sb, 0, 0, 10);\n\n store.push(sb);\n});\n
\nUse of SlowBuffer
should be used only as a last resort after a developer\nhas observed undue memory retention in their applications.
Allocates a new Buffer
of size
bytes. If the size
is larger than\nbuffer.kMaxLength
or smaller than 0, a RangeError
will be thrown.\nA zero-length Buffer
will be created if size
is 0.
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.
Example:
\nconst SlowBuffer = require('buffer').SlowBuffer;\n\nconst buf = new SlowBuffer(5);\n\n// Prints: (contents may vary): <Buffer 78 e0 82 02 01>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00>\nconsole.log(buf);\n
\n\n\n"
},
{
"params": [
{
"name": "size"
}
],
"desc": "Allocates a new Buffer
of size
bytes. If the size
is larger than\nbuffer.kMaxLength
or smaller than 0, a RangeError
will be thrown.\nA zero-length Buffer
will be created if size
is 0.
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.
Example:
\nconst SlowBuffer = require('buffer').SlowBuffer;\n\nconst buf = new SlowBuffer(5);\n\n// Prints: (contents may vary): <Buffer 78 e0 82 02 01>\nconsole.log(buf);\n\nbuf.fill(0);\n\n// Prints: <Buffer 00 00 00 00 00>\nconsole.log(buf);\n
\n\n\n"
}
]
}
],
"properties": [
{
"textRaw": "`INSPECT_MAX_BYTES` {Integer} **Default:** `50` ",
"type": "Integer",
"name": "INSPECT_MAX_BYTES",
"meta": {
"added": [
"v0.5.4"
]
},
"desc": "Returns the maximum number of bytes that will be returned when\nbuf.inspect()
is called. This can be overridden by user modules. See\nutil.inspect()
for more details on buf.inspect()
behavior.
Note that this is a property on the buffer
module returned by\nrequire('buffer')
, not on the Buffer
global or a Buffer
instance.
On 32-bit architectures, this value is (2^30)-1
(~1GB).\nOn 64-bit architectures, this value is (2^31)-1
(~2GB).
Note that this is a property on the buffer
module returned by\nrequire('buffer')
, not on the Buffer
global or a Buffer
instance.
Re-encodes the given Buffer
instance from one character encoding to another.\nReturns a new Buffer
instance.
Throws if the fromEnc
or toEnc
specify invalid character encodings or if\nconversion from fromEnc
to toEnc
is not permitted.
The transcoding process will use substitution characters if a given byte\nsequence cannot be adequately represented in the target encoding. For instance:
\nconst buffer = require('buffer');\n\nconst newBuf = buffer.transcode(Buffer.from('€'), 'utf8', 'ascii');\nconsole.log(newBuf.toString('ascii'));\n// Prints: '?'\n
\nBecause the Euro (€
) sign is not representable in US-ASCII, it is replaced\nwith ?
in the transcoded Buffer
.
Note that this is a property on the buffer
module returned by\nrequire('buffer')
, not on the Buffer
global or a Buffer
instance.
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:
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
\nBy 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.
The child_process.spawn()
method spawns the child process asynchronously,\nwithout blocking the Node.js event loop. The child_process.spawnSync()
\nfunction provides equivalent functionality in a synchronous manner that blocks\nthe event loop until the spawned process either exits or is terminated.
For convenience, the child_process
module provides a handful of synchronous\nand asynchronous alternatives to child_process.spawn()
and\nchild_process.spawnSync()
. Note that each of these alternatives are\nimplemented on top of child_process.spawn()
or child_process.spawnSync()
.
child_process.exec()
: spawns a shell and runs a command within that shell,\npassing the stdout
and stderr
to a callback function when complete.child_process.execFile()
: similar to child_process.exec()
except that\nit spawns the command directly without first spawning a shell.child_process.fork()
: spawns a new Node.js process and invokes a\nspecified module with an IPC communication channel established that allows\nsending messages between parent and child.child_process.execSync()
: a synchronous version of\nchild_process.exec()
that will block the Node.js event loop.child_process.execFileSync()
: a synchronous version of\nchild_process.execFile()
that will block the Node.js event loop.For certain use cases, such as automating shell scripts, the\nsynchronous counterparts may be more convenient. In many cases, however,\nthe synchronous methods can have significant impact on performance due to\nstalling the event loop while spawned processes complete.
\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.
Each of the methods returns a ChildProcess
instance. These objects\nimplement the Node.js EventEmitter
API, allowing the parent process to\nregister listener functions that are called when certain events occur during\nthe life cycle of the child process.
The child_process.exec()
and child_process.execFile()
methods additionally\nallow for an optional callback
function to be specified that is invoked\nwhen the child process terminates.
The importance of the distinction between child_process.exec()
and\nchild_process.execFile()
can vary based on platform. On Unix-type 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). In any case, if the script filename contains\nspaces it needs to be quoted.
// On Windows Only ...\nconst spawn = require('child_process').spawn;\nconst bat = spawn('cmd.exe', ['/c', 'my.bat']);\n\nbat.stdout.on('data', (data) => {\n console.log(data.toString());\n});\n\nbat.stderr.on('data', (data) => {\n console.log(data.toString());\n});\n\nbat.on('exit', (code) => {\n console.log(`Child exited with code ${code}`);\n});\n\n// OR...\nconst exec = require('child_process').exec;\nexec('my.bat', (err, stdout, stderr) => {\n if (err) {\n console.error(err);\n return;\n }\n console.log(stdout);\n});\n\n// Script with spaces in the filename:\nconst bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });\n// or:\nexec('"my script.cmd" a b', (err, stdout, stderr) => {\n // ...\n});\n
\n",
"type": "module",
"displayName": "Spawning `.bat` and `.cmd` files on Windows"
}
],
"methods": [
{
"textRaw": "child_process.exec(command[, options][, callback])",
"type": "method",
"name": "exec",
"meta": {
"added": [
"v0.1.90"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {ChildProcess} ",
"name": "return",
"type": "ChildProcess"
},
"params": [
{
"textRaw": "`command` {String} The command to run, with space-separated arguments ",
"name": "command",
"type": "String",
"desc": "The command to run, with space-separated arguments"
},
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`cwd` {String} Current working directory of the child process ",
"name": "cwd",
"type": "String",
"desc": "Current working directory of the child process"
},
{
"textRaw": "`env` {Object} Environment key-value pairs ",
"name": "env",
"type": "Object",
"desc": "Environment key-value pairs"
},
{
"textRaw": "`encoding` {String} (Default: `'utf8'`) ",
"name": "encoding",
"type": "String",
"desc": "(Default: `'utf8'`)"
},
{
"textRaw": "`shell` {String} Shell to execute the command with (Default: `'/bin/sh'` on UNIX, `'cmd.exe'` on Windows, The shell should understand the `-c` switch on UNIX or `/d /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 `/d /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": "[",
"default": "200*1024",
"desc": "maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed"
},
{
"textRaw": "`killSignal` {String|Integer} (Default: `'SIGTERM'`) ",
"name": "killSignal",
"type": "String|Integer",
"desc": "(Default: `'SIGTERM'`)"
},
{
"textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ",
"name": "uid",
"type": "Number",
"desc": "Sets the user identity of the process. (See setuid(2).)"
},
{
"textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ",
"name": "gid",
"type": "Number",
"desc": "Sets the group identity of the process. (See setgid(2).)"
}
],
"name": "options",
"type": "Object",
"optional": true
},
{
"textRaw": "`callback` {Function} called with the output when process terminates ",
"options": [
{
"textRaw": "`error` {Error} ",
"name": "error",
"type": "Error"
},
{
"textRaw": "`stdout` {String|Buffer} ",
"name": "stdout",
"type": "String|Buffer"
},
{
"textRaw": "`stderr` {String|Buffer} ",
"name": "stderr",
"type": "String|Buffer"
}
],
"name": "callback",
"type": "Function",
"desc": "called with the output when process terminates",
"optional": true
}
]
},
{
"params": [
{
"name": "command"
},
{
"name": "options",
"optional": true
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Spawns a shell then executes the command
within that shell, buffering any\ngenerated output.
Note: Never pass unsanitised user input to this function. Any input\ncontaining shell metacharacters may be used to trigger arbitrary command\nexecution.
\nconst exec = require('child_process').exec;\nexec('cat *.js bad_file | wc -l', (error, stdout, stderr) => {\n if (error) {\n console.error(`exec error: ${error}`);\n return;\n }\n console.log(`stdout: ${stdout}`);\n console.log(`stderr: ${stderr}`);\n});\n
\nIf a callback
function is provided, it is called with the arguments\n(error, stdout, stderr)
. On success, error
will be null
. On error,\nerror
will be an instance of Error
. The error.code
property will be\nthe exit code of the 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.
The stdout
and stderr
arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding
option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding
is 'buffer'
, or an unrecognized character\nencoding, Buffer
objects will be passed to the callback instead.
The options
argument may be passed as the second argument to customize how\nthe process is spawned. The default options are:
{\n encoding: 'utf8',\n timeout: 0,\n maxBuffer: 200*1024,\n killSignal: 'SIGTERM',\n cwd: null,\n env: null\n}\n
\nIf 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.
Note: Unlike the exec(3) POSIX system call, child_process.exec()
does not\nreplace the existing process and uses a shell to execute the command.
The child_process.execFile()
function is similar to child_process.exec()
\nexcept that it does not spawn a shell. Rather, the specified executable file
\nis spawned directly as a new process making it slightly more efficient than\nchild_process.exec()
.
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.
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
\nThe stdout
and stderr
arguments passed to the callback will contain the\nstdout and stderr output of the child process. By default, Node.js will decode\nthe output as UTF-8 and pass strings to the callback. The encoding
option\ncan be used to specify the character encoding used to decode the stdout and\nstderr output. If encoding
is 'buffer'
, or an unrecognized character\nencoding, Buffer
objects will be passed to the callback instead.
The child_process.fork()
method is a special case of\nchild_process.spawn()
used specifically to spawn new Node.js processes.\nLike child_process.spawn()
, a ChildProcess
object is returned. The returned\nChildProcess
will have an additional communication channel built-in that\nallows messages to be passed back and forth between the parent and child. See\nchild.send()
for details.
It is important to keep in mind that spawned Node.js child processes are\nindependent of the parent with exception of the IPC communication channel\nthat is established between the two. Each process has its own memory, with\ntheir own V8 instances. Because of the additional resource allocations\nrequired, spawning a large number of child Node.js processes is not\nrecommended.
\nBy default, child_process.fork()
will spawn new Node.js instances using the\nprocess.execPath
of the parent process. The execPath
property in the\noptions
object allows for an alternative execution path to be used.
Node.js processes launched with a custom execPath
will communicate with the\nparent process using the file descriptor (fd) identified using the\nenvironment variable NODE_CHANNEL_FD
on the child process. The input and\noutput on this fd is expected to be line delimited JSON objects.
Note: Unlike the fork(2) POSIX system call, child_process.fork()
does\nnot clone the current process.
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.
Note: If the shell
option is enabled, do not pass unsanitised user input to\nthis function. Any input containing shell metacharacters may be used to\ntrigger arbitrary command execution.
A third argument may be used to specify additional options, with these defaults:
\n{\n cwd: undefined,\n env: process.env\n}\n
\nUse cwd
to specify the working directory from which the process is spawned.\nIf not given, the default is to inherit the current working directory.
Use env
to specify environment variables that will be visible to the new\nprocess, the default is process.env
.
Example of running ls -lh /usr
, capturing stdout
, stderr
, and the\nexit code:
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
\nExample: A very elaborate way to run ps ax | grep ssh
const spawn = require('child_process').spawn;\nconst ps = spawn('ps', ['ax']);\nconst grep = spawn('grep', ['ssh']);\n\nps.stdout.on('data', (data) => {\n grep.stdin.write(data);\n});\n\nps.stderr.on('data', (data) => {\n console.log(`ps stderr: ${data}`);\n});\n\nps.on('close', (code) => {\n if (code !== 0) {\n console.log(`ps process exited with code ${code}`);\n }\n grep.stdin.end();\n});\n\ngrep.stdout.on('data', (data) => {\n console.log(data.toString());\n});\n\ngrep.stderr.on('data', (data) => {\n console.log(`grep stderr: ${data}`);\n});\n\ngrep.on('close', (code) => {\n if (code !== 0) {\n console.log(`grep process exited with code ${code}`);\n }\n});\n
\nExample of checking for failed exec:
\nconst 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
\nNote: Certain platforms (OS X, Linux) will use the value of argv[0]
for the\nprocess title while others (Windows, SunOS) will use command
.
Note: Node.js currently overwrites argv[0]
with process.execPath
on\nstartup, so process.argv[0]
in a Node.js child process will not match the\nargv0
parameter passed to spawn
from the parent, retrieve it with the\nprocess.argv0
property instead.
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.
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.
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.
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.
Example of a long-running process, by detaching and also ignoring its parent\nstdio
file descriptors, in order to ignore the parent's termination:
const spawn = require('child_process').spawn;\n\nconst child = spawn(process.argv[0], ['child_program.js'], {\n detached: true,\n stdio: 'ignore'\n});\n\nchild.unref();\n
\nAlternatively one can redirect the child process' output into files:
\nconst 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
\n"
},
{
"textRaw": "options.stdio",
"name": "stdio",
"meta": {
"added": [
"v0.7.10"
]
},
"desc": "The options.stdio
option is used to configure the pipes that are established\nbetween the parent and child process. By default, the child's stdin, stdout,\nand stderr are redirected to corresponding 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']
.
For convenience, options.stdio
may be one of the following strings:
'pipe'
- equivalent to ['pipe', 'pipe', 'pipe']
(the default)'ignore'
- equivalent to ['ignore', 'ignore', 'ignore']
'inherit'
- equivalent to [process.stdin, process.stdout, process.stderr]
\n or [0,1,2]
Otherwise, the value of options.stdio
is an array where each index corresponds\nto an fd in the child. The fds 0, 1, and 2 correspond to stdin, stdout,\nand stderr, respectively. Additional fds can be specified to create additional\npipes between the parent and child. The value is one of the following:
'pipe'
- Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process
object as child.stdio[fd]
. Pipes created for\nfds 0 - 2 are also available as child.stdin
, child.stdout
\nand child.stderr
, respectively.'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 child.send()
method.\nIf the child writes JSON messages to this file descriptor, the\nchild.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.'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.stdio
array. Note that the stream must\nhave an underlying descriptor (file streams do not until the 'open'
\nevent has occurred).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'
.Example:
\nconst 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
\nIt is worth noting that when an IPC channel is established between the\nparent and child processes, and the child is a Node.js process, the child\nis launched with the IPC channel unreferenced (using unref()
) until the\nchild registers an event handler for the process.on('disconnect')
event.\nThis allows the child to exit normally without the process being held open\nby the open IPC channel.
See also: child_process.exec()
and child_process.fork()
The child_process.spawnSync()
, child_process.execSync()
, and\nchild_process.execFileSync()
methods are synchronous and WILL block\nthe Node.js event loop, pausing execution of any additional code until the\nspawned process exits.
Blocking calls like these are mostly useful for simplifying general purpose\nscripting tasks and for simplifying the loading/processing of application\nconfiguration at startup.
\n", "methods": [ { "textRaw": "child_process.execFileSync(file[, args][, options])", "type": "method", "name": "execFileSync", "meta": { "added": [ "v0.11.12" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer|String} The stdout from the command ", "name": "return", "type": "Buffer|String", "desc": "The stdout from the command" }, "params": [ { "textRaw": "`file` {String} The name or path of the executable file to run ", "name": "file", "type": "String", "desc": "The name or path of the executable file to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`input` {String|Buffer} The value which will be passed as stdin to the spawned process ", "options": [ { "textRaw": "supplying this value will override `stdio[0]` ", "name": "supplying", "desc": "this value will override `stdio[0]`" } ], "name": "input", "type": "String|Buffer", "desc": "The value which will be passed as stdin to the spawned process" }, { "textRaw": "`stdio` {String | Array} Child's stdio configuration. (Default: `'pipe'`) ", "options": [ { "textRaw": "`stderr` by default will be output to the parent process' stderr unless `stdio` is specified ", "name": "stderr", "desc": "by default will be output to the parent process' stderr unless `stdio` is specified" } ], "name": "stdio", "type": "String | Array", "desc": "Child's stdio configuration. (Default: `'pipe'`)" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", "name": "uid", "type": "Number", "desc": "Sets the user identity of the process. (See setuid(2).)" }, { "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", "name": "gid", "type": "Number", "desc": "Sets the group identity of the process. (See setgid(2).)" }, { "textRaw": "`timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: `undefined`) ", "name": "timeout", "default": "undefined", "type": "Number", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {String|Integer} The signal value to be used when the spawned process will be killed. (Default: `'SIGTERM'`) ", "name": "killSignal", "type": "String|Integer", "desc": "The signal value to be used when the spawned process will be killed. (Default: `'SIGTERM'`)" }, { "textRaw": "[`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed ", "name": "[", "desc": "maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`encoding` {String} The encoding used for all stdio inputs and outputs. (Default: `'buffer'`) ", "name": "encoding", "type": "String", "desc": "The encoding used for all stdio inputs and outputs. (Default: `'buffer'`)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "The child_process.execFileSync()
method is generally identical to\nchild_process.execFile()
with the exception that the method will not return\nuntil the child process has fully closed. When a timeout has been encountered\nand killSignal
is sent, the method won't return until the process has\ncompletely exited. Note that if the child process intercepts and handles\nthe SIGTERM
signal and does not exit, the parent process will still wait\nuntil the child process has exited.
If the process times out, or has a non-zero exit code, this method will\nthrow. The Error
object will contain the entire result from\nchild_process.spawnSync()
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.
If the process times out, or has a non-zero exit code, this method will\nthrow. The Error
object will contain the entire result from\nchild_process.spawnSync()
Note: Never pass unsanitised user input to this function. Any input\ncontaining shell metacharacters may be used to trigger arbitrary command\nexecution.
\n" }, { "textRaw": "child_process.spawnSync(command[, args][, options])", "type": "method", "name": "spawnSync", "meta": { "added": [ "v0.11.12" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "options": [ { "textRaw": "`pid` {Number} Pid of the child process ", "name": "pid", "type": "Number", "desc": "Pid of the child process" }, { "textRaw": "`output` {Array} Array of results from stdio output ", "name": "output", "type": "Array", "desc": "Array of results from stdio output" }, { "textRaw": "`stdout` {Buffer|String} The contents of `output[1]` ", "name": "stdout", "type": "Buffer|String", "desc": "The contents of `output[1]`" }, { "textRaw": "`stderr` {Buffer|String} The contents of `output[2]` ", "name": "stderr", "type": "Buffer|String", "desc": "The contents of `output[2]`" }, { "textRaw": "`status` {Number} The exit code of the child process ", "name": "status", "type": "Number", "desc": "The exit code of the child process" }, { "textRaw": "`signal` {String} The signal used to kill the child process ", "name": "signal", "type": "String", "desc": "The signal used to kill the child process" }, { "textRaw": "`error` {Error} The error object if the child process failed or timed out ", "name": "error", "type": "Error", "desc": "The error object if the child process failed or timed out" } ], "name": "return", "type": "Object" }, "params": [ { "textRaw": "`command` {String} The command to run ", "name": "command", "type": "String", "desc": "The command to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`input` {String|Buffer} The value which will be passed as stdin to the spawned process ", "options": [ { "textRaw": "supplying this value will override `stdio[0]` ", "name": "supplying", "desc": "this value will override `stdio[0]`" } ], "name": "input", "type": "String|Buffer", "desc": "The value which will be passed as stdin to the spawned process" }, { "textRaw": "`stdio` {String | Array} Child's stdio configuration. ", "name": "stdio", "type": "String | Array", "desc": "Child's stdio configuration." }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", "name": "uid", "type": "Number", "desc": "Sets the user identity of the process. (See setuid(2).)" }, { "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", "name": "gid", "type": "Number", "desc": "Sets the group identity of the process. (See setgid(2).)" }, { "textRaw": "`timeout` {Number} In milliseconds the maximum amount of time the process is allowed to run. (Default: `undefined`) ", "name": "timeout", "default": "undefined", "type": "Number", "desc": "In milliseconds the maximum amount of time the process is allowed to run." }, { "textRaw": "`killSignal` {String|Integer} The signal value to be used when the spawned process will be killed. (Default: `'SIGTERM'`) ", "name": "killSignal", "type": "String|Integer", "desc": "The signal value to be used when the spawned process will be killed. (Default: `'SIGTERM'`)" }, { "textRaw": "[`maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed ", "name": "[", "desc": "maxBuffer`][] {Number} largest amount of data (in bytes) allowed on stdout or stderr - if exceeded child process is killed" }, { "textRaw": "`encoding` {String} The encoding used for all stdio inputs and outputs. (Default: `'buffer'`) ", "name": "encoding", "type": "String", "desc": "The encoding used for all stdio inputs and outputs. (Default: `'buffer'`)" }, { "textRaw": "`shell` {Boolean|String} If `true`, runs `command` inside of a shell. Uses `'/bin/sh'` on UNIX, and `'cmd.exe'` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX, or `/d /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 `/d /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.
Note: If the shell
option is enabled, do not pass unsanitised user input to\nthis function. Any input containing shell metacharacters may be used to\ntrigger arbitrary command execution.
It is important to keep in mind that the maxBuffer
option specifies the\nlargest number of octets allowed on stdout
or stderr
. If this value is\nexceeded, then the child process is terminated. This particularly impacts\noutput that includes multibyte character encodings such as UTF-8 or UTF-16.\nFor instance, the following will output 13 UTF-8 encoded octets to stdout
\nalthough there are only 4 characters:
console.log('中文测试');\n
\n\n\n",
"type": "module",
"displayName": "`maxBuffer` and Unicode"
}
],
"classes": [
{
"textRaw": "Class: ChildProcess",
"type": "class",
"name": "ChildProcess",
"meta": {
"added": [
"v2.2.0"
]
},
"desc": "Instances of the ChildProcess
class are EventEmitters
that represent\nspawned child processes.
Instances of ChildProcess
are not intended to be created directly. Rather,\nuse the child_process.spawn()
, child_process.exec()
,\nchild_process.execFile()
, or child_process.fork()
methods to create\ninstances of ChildProcess
.
The 'close'
event is emitted 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.
The 'disconnect'
event is emitted after calling the\nchild.disconnect()
method in parent process or process.disconnect()
in child process. After\ndisconnecting it is no longer possible to send or receive messages, and the\nchild.connected
property is false
.
The 'error'
event is emitted whenever:
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.
See also child.kill()
and child.send()
.
The 'exit'
event is emitted after the child process ends. If the process\nexited, code
is the final exit code of the process, otherwise null
. If the\nprocess terminated due to receipt of a signal, signal
is the string name of\nthe signal, otherwise null
. One of the two will always be non-null.
Note that when the 'exit'
event is triggered, child process stdio streams\nmight still be open.
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.
See waitpid(2).
\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.5.9" ] }, "params": [], "desc": "The 'message'
event is triggered when a child process uses process.send()
\nto send messages.
The child.channel
property is a reference to the child's IPC channel. If no\nIPC channel currently exists, this property is undefined
.
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.
Returns the process identifier (PID) of the child process.
\nExample:
\nconst spawn = require('child_process').spawn;\nconst grep = spawn('grep', ['ssh']);\n\nconsole.log(`Spawned child pid: ${grep.pid}`);\ngrep.stdin.end();\n
\n",
"shortDesc": "Integer"
},
{
"textRaw": "`stderr` {stream.Readable} ",
"type": "stream.Readable",
"name": "stderr",
"meta": {
"added": [
"v0.1.90"
]
},
"desc": "A Readable Stream
that represents the child process's stderr
.
If the child was spawned with stdio[2]
set to anything other than 'pipe'
,\nthen this will be undefined
.
child.stderr
is an alias for child.stdio[2]
. Both properties will refer to\nthe same value.
A Writable Stream
that represents the child process's stdin
.
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()
.
If the child was spawned with stdio[0]
set to anything other than 'pipe'
,\nthen this will be undefined
.
child.stdin
is an alias for child.stdio[0]
. Both properties will refer to\nthe same value.
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.
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
.
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 parent's stdin for child\n 'pipe', // Pipe child's stdout to parent\n fs.openSync('err.out', 'w') // Direct child's stderr to a file\n ]\n});\n\nassert.strictEqual(child.stdio[0], null);\nassert.strictEqual(child.stdio[0], child.stdin);\n\nassert(child.stdout);\nassert.strictEqual(child.stdio[1], child.stdout);\n\nassert.strictEqual(child.stdio[2], null);\nassert.strictEqual(child.stdio[2], child.stderr);\n
\n"
},
{
"textRaw": "`stdout` {stream.Readable} ",
"type": "stream.Readable",
"name": "stdout",
"meta": {
"added": [
"v0.1.90"
]
},
"desc": "A Readable Stream
that represents the child process's stdout
.
If the child was spawned with stdio[1]
set to anything other than 'pipe'
,\nthen this will be undefined
.
child.stdout
is an alias for child.stdio[1]
. Both properties will refer\nto the same value.
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.
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()
.
Note that when the child process is a Node.js instance (e.g. spawned using\nchild_process.fork()
), the process.disconnect()
method can be invoked\nwithin the child process to close the IPC channel as well.
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.
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
\nThe 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.
Note that while the function is called kill
, the signal delivered to the\nchild process may not actually terminate the process.
See kill(2) for reference.
\nAlso note: on Linux, child processes of child processes will not be terminated\nwhen attempting to kill their parent. This is likely to happen when running a\nnew process in a shell or with use of the shell
option of ChildProcess
, such\nas in this example:
'use strict';\nconst spawn = require('child_process').spawn;\n\nconst child = spawn('sh', ['-c',\n `node -e "setInterval(() => {\n console.log(process.pid, 'is alive')\n }, 500);"`\n ], {\n stdio: ['inherit', 'inherit', 'inherit']\n });\n\nsetTimeout(() => {\n child.kill(); // does not terminate the node process in the shell\n}, 2000);\n
\n"
},
{
"textRaw": "child.send(message[, sendHandle[, options]][, callback])",
"type": "method",
"name": "send",
"meta": {
"added": [
"v0.5.9"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Boolean} ",
"name": "return",
"type": "Boolean"
},
"params": [
{
"textRaw": "`message` {Object} ",
"name": "message",
"type": "Object"
},
{
"textRaw": "`sendHandle` {Handle} ",
"name": "sendHandle",
"type": "Handle",
"optional": true
},
{
"textRaw": "`options` {Object} ",
"name": "options",
"type": "Object",
"optional": true
},
{
"textRaw": "`callback` {Function} ",
"name": "callback",
"type": "Function",
"optional": true
}
]
},
{
"params": [
{
"name": "message"
},
{
"name": "sendHandle",
"optional": true
},
{
"name": "options",
"optional": true
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "When an IPC channel has been established between the parent and child (\ni.e. when using child_process.fork()
), the 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.
For example, in the parent script:
\nconst 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
\nAnd then the child script, 'sub.js'
might look like this:
process.on('message', (m) => {\n console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });\n
\nChild Node.js processes will have a process.send()
method of their own that\nallows the child to send messages back to the parent.
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.
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. Any data that is received\nand buffered in the socket will not be sent to the child.
The options
argument, if present, is an object used to parameterize the\nsending of certain types of handles. options
supports the following\nproperties:
keepOpen
- A Boolean value that can be used when passing instances of\nnet.Socket
. When true
, the socket is kept open in the sending process.\nDefaults to false
.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.
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.
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.
The sendHandle
argument can be used, for instance, to pass the handle of\na TCP server object to the child process as illustrated in the example below:
const 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
\nThe child would then receive the server object as:
\nprocess.on('message', (m, server) => {\n if (m === 'server') {\n server.on('connection', (socket) => {\n socket.end('handled by child');\n });\n }\n});\n
\nOnce the server is now shared between the parent and child, some connections\ncan be handled by the parent and some by the child.
\nWhile the example above uses a server created using the 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.
Similarly, the sendHandler
argument can be used to pass the handle of a\nsocket to the child process. The example below spawns two children that each\nhandle connections with "normal" or "special" priority:
const 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
\nThe child.js
would receive the socket handle as the second argument passed\nto the event callback function:
process.on('message', (m, socket) => {\n if (m === 'socket') {\n socket.end(`Request handled with ${process.argv[2]} priority`);\n }\n});\n
\nOnce 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.
Note: this function uses JSON.stringify()
internally to serialize the\nmessage
.
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.
\nThe cluster module allows you to easily create child processes that\nall share server ports.
\nconst cluster = require('cluster');\nconst http = require('http');\nconst numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n console.log(`Master ${process.pid} is running`);\n\n // Fork workers.\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n cluster.on('exit', (worker, code, signal) => {\n console.log(`worker ${worker.process.pid} died`);\n });\n} else {\n // Workers can share any TCP connection\n // In this case it is an HTTP server\n http.createServer((req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n }).listen(8000);\n\n console.log(`Worker ${process.pid} started`);\n}\n
\nRunning Node.js will now share port 8000 between the workers:
\n$ node server.js\nMaster 3596 is running\nWorker 4324 started\nWorker 4520 started\nWorker 6056 started\nWorker 5644 started\n
\nPlease note that on Windows, it is not yet possible to set up a named pipe\nserver in a worker.
\n", "miscs": [ { "textRaw": "How It Works", "name": "How It Works", "type": "misc", "desc": "The worker processes are spawned using the child_process.fork()
method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.
The cluster module supports two methods of distributing incoming\nconnections.
\nThe first one (and the default one on all platforms except Windows),\nis the round-robin approach, where the 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.
\nThe second approach is where the master process creates the listen\nsocket and sends it to interested workers. The workers then accept\nincoming connections directly.
\nThe second approach should, in theory, give the best performance.\nIn practice however, distribution tends to be very unbalanced due\nto operating system scheduler vagaries. Loads have been observed\nwhere over 70% of all connections ended up in just two processes,\nout of a total of eight.
\nBecause server.listen()
hands off most of the work to the master\nprocess, there are three cases where the behavior between a normal\nNode.js process and a cluster worker differs:
server.listen({fd: 7})
Because the message is passed to the 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.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.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.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.
\nBecause 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" } ], "classes": [ { "textRaw": "Class: Worker", "type": "class", "name": "Worker", "meta": { "added": [ "v0.7.0" ] }, "desc": "A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers
. In a worker\nit can be obtained using cluster.worker
.
Similar to the cluster.on('disconnect')
event, but specific to this worker.
cluster.fork().on('disconnect', () => {\n // Worker has disconnected\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'error'",
"type": "event",
"name": "error",
"meta": {
"added": [
"v0.7.3"
]
},
"desc": "This event is the same as the one provided by child_process.fork()
.
In a worker you can also use process.on('error')
.
Similar to the cluster.on('exit')
event, but specific to this worker.
const worker = cluster.fork();\nworker.on('exit', (code, signal) => {\n if (signal) {\n console.log(`worker was killed by signal: ${signal}`);\n } else if (code !== 0) {\n console.log(`worker exited with error code: ${code}`);\n } else {\n console.log('worker success!');\n }\n});\n
\n"
},
{
"textRaw": "Event: 'listening'",
"type": "event",
"name": "listening",
"meta": {
"added": [
"v0.7.0"
]
},
"params": [],
"desc": "Similar to the cluster.on('listening')
event, but specific to this worker.
cluster.fork().on('listening', (address) => {\n // Worker is listening\n});\n
\nIt is not emitted in the worker.
\n" }, { "textRaw": "Event: 'message'", "type": "event", "name": "message", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "Similar to the cluster.on('message')
event, but specific to this worker. In a\nworker you can also use process.on('message')
.
As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:
\nconst cluster = require('cluster');\nconst http = require('http');\n\nif (cluster.isMaster) {\n\n // Keep track of http requests\n let numReqs = 0;\n setInterval(() => {\n console.log(`numReqs = ${numReqs}`);\n }, 1000);\n\n // Count requests\n function messageHandler(msg) {\n if (msg.cmd && msg.cmd === 'notifyRequest') {\n numReqs += 1;\n }\n }\n\n // Start workers and listen for messages containing notifyRequest\n const numCPUs = require('os').cpus().length;\n for (let i = 0; i < numCPUs; i++) {\n cluster.fork();\n }\n\n for (const id in cluster.workers) {\n cluster.workers[id].on('message', messageHandler);\n }\n\n} else {\n\n // Worker processes have a http server.\n http.Server((req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n\n // notify master about the request\n process.send({ cmd: 'notifyRequest' });\n }).listen(8000);\n}\n
\n"
},
{
"textRaw": "Event: 'online'",
"type": "event",
"name": "online",
"meta": {
"added": [
"v0.7.0"
]
},
"desc": "Similar to the cluster.on('online')
event, but specific to this worker.
cluster.fork().on('online', () => {\n // Worker is online\n});\n
\nIt is not emitted in the worker.
\n", "params": [] } ], "methods": [ { "textRaw": "worker.disconnect()", "type": "method", "name": "disconnect", "meta": { "added": [ "v0.7.7" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Worker} A reference to `worker`. ", "name": "return", "type": "Worker", "desc": "A reference to `worker`." }, "params": [] }, { "params": [] } ], "desc": "In a worker, this function will close all servers, wait for the 'close'
event on\nthose servers, and then disconnect the IPC channel.
In the master, an internal message is sent to the worker causing it to call\n.disconnect()
on itself.
Causes .exitedAfterDisconnect
to be set.
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.
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.
\nNote that in a worker, process.disconnect
exists, but it is not this function,\nit is disconnect
.
Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe 'disconnect'
event has not been emitted after some time.
if (cluster.isMaster) {\n const worker = cluster.fork();\n let timeout;\n\n worker.on('listening', (address) => {\n worker.send('shutdown');\n worker.disconnect();\n timeout = setTimeout(() => {\n worker.kill();\n }, 2000);\n });\n\n worker.on('disconnect', () => {\n clearTimeout(timeout);\n });\n\n} else if (cluster.isWorker) {\n const net = require('net');\n const server = net.createServer((socket) => {\n // connections never end\n });\n\n server.listen(8000);\n\n process.on('message', (msg) => {\n if (msg === 'shutdown') {\n // initiate graceful close of any connections to server\n }\n });\n}\n
\n"
},
{
"textRaw": "worker.isConnected()",
"type": "method",
"name": "isConnected",
"meta": {
"added": [
"v0.11.14"
]
},
"desc": "This function returns true
if the worker is connected to its master via its IPC\nchannel, false
otherwise. A worker is connected to its master after it's been\ncreated. It is disconnected after the 'disconnect'
event is emitted.
This function returns true
if the worker's process has terminated (either\nbecause of exiting or being signaled). Otherwise, it returns false
.
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
.
Causes .exitedAfterDisconnect
to be set.
This method is aliased as worker.destroy()
for backwards compatibility.
Note that in a worker, process.kill()
exists, but it is not this function,\nit is kill
.
Send a message to a worker or master, optionally with a handle.
\nIn the master this sends a message to a specific worker. It is identical to\nChildProcess.send()
.
In a worker this sends a message to the master. It is identical to\nprocess.send()
.
This example will echo back all messages from the master:
\nif (cluster.isMaster) {\n const worker = cluster.fork();\n worker.send('hi there');\n\n} else if (cluster.isWorker) {\n process.on('message', (msg) => {\n process.send(msg);\n });\n}\n
\n"
}
],
"properties": [
{
"textRaw": "`exitedAfterDisconnect` {Boolean} ",
"type": "Boolean",
"name": "exitedAfterDisconnect",
"meta": {
"added": [
"v6.0.0"
]
},
"desc": "Set by calling .kill()
or .disconnect()
. Until then, it is undefined
.
The boolean worker.exitedAfterDisconnect
lets you distinguish between voluntary\nand accidental exit, the master may choose not to respawn a worker based on\nthis value.
cluster.on('exit', (worker, code, signal) => {\n if (worker.exitedAfterDisconnect === true) {\n console.log('Oh, it was just voluntary – no need to worry');\n }\n});\n\n// kill worker\nworker.kill();\n
\n"
},
{
"textRaw": "`id` {Number} ",
"type": "Number",
"name": "id",
"meta": {
"added": [
"v0.8.0"
]
},
"desc": "Each new worker is given its own unique id, this id is stored in the\nid
.
While a worker is alive, this is the key that indexes it in\ncluster.workers
\n" }, { "textRaw": "`process` {ChildProcess} ", "type": "ChildProcess", "name": "process", "meta": { "added": [ "v0.7.0" ] }, "desc": "All workers are created using child_process.fork()
, the returned object\nfrom this function is stored as .process
. In a worker, the global process
\nis stored.
See: Child Process module
\nNote that workers will call process.exit(0)
if the 'disconnect'
event occurs\non process
and .exitedAfterDisconnect
is not true
. This protects against\naccidental disconnection.
An alias to worker.exitedAfterDisconnect
.
Set by calling .kill()
or .disconnect()
. Until then, it is undefined
.
The boolean worker.suicide
lets you distinguish between voluntary\nand accidental exit, the master may choose not to respawn a worker based on\nthis value.
cluster.on('exit', (worker, code, signal) => {\n if (worker.suicide === true) {\n console.log('Oh, it was just voluntary – no need to worry');\n }\n});\n\n// kill worker\nworker.kill();\n
\nThis API only exists for backwards compatibility and will be removed in the\nfuture.
\n" } ] } ], "events": [ { "textRaw": "Event: 'disconnect'", "type": "event", "name": "disconnect", "meta": { "added": [ "v0.7.9" ] }, "params": [], "desc": "Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).
\nThere 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.
cluster.on('disconnect', (worker) => {\n console.log(`The worker #${worker.id} has disconnected`);\n});\n
\n"
},
{
"textRaw": "Event: 'exit'",
"type": "event",
"name": "exit",
"meta": {
"added": [
"v0.7.9"
]
},
"params": [],
"desc": "When any of the workers die the cluster module will emit the 'exit'
event.
This can be used to restart the worker by calling .fork()
again.
cluster.on('exit', (worker, code, signal) => {\n console.log('worker %d died (%s). restarting...',\n worker.process.pid, signal || code);\n cluster.fork();\n});\n
\nSee child_process event: 'exit'.
\n" }, { "textRaw": "Event: 'fork'", "type": "event", "name": "fork", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "When a new worker is forked the cluster module will emit a 'fork'
event.\nThis can be used to log worker activity, and create your own timeout.
const timeouts = [];\nfunction errorMsg() {\n console.error('Something must be wrong with the connection ...');\n}\n\ncluster.on('fork', (worker) => {\n timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', (worker, address) => {\n clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', (worker, code, signal) => {\n clearTimeout(timeouts[worker.id]);\n errorMsg();\n});\n
\n"
},
{
"textRaw": "Event: 'listening'",
"type": "event",
"name": "listening",
"meta": {
"added": [
"v0.7.0"
]
},
"params": [],
"desc": "After calling listen()
from a worker, when the 'listening'
event is emitted on\nthe server, a 'listening'
event will also be emitted on cluster
in the master.
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.
cluster.on('listening', (worker, address) => {\n console.log(\n `A worker is now connected to ${address.address}:${address.port}`);\n});\n
\nThe addressType
is one of:
4
(TCPv4)6
(TCPv6)-1
(unix domain socket)"udp4"
or "udp6"
(UDP v4 or v6)Emitted when the cluster master receives a message from any worker.
\nSee child_process event: 'message'.
\nBefore Node.js v6.0, this event emitted only the message and the handle,\nbut not the worker object, contrary to what the documentation stated.
\nIf you need to support older versions and don't need the worker object,\nyou can work around the discrepancy by checking the number of arguments:
\ncluster.on('message', (worker, message, handle) => {\n if (arguments.length === 2) {\n handle = message;\n message = worker;\n worker = undefined;\n }\n // ...\n});\n
\n"
},
{
"textRaw": "Event: 'online'",
"type": "event",
"name": "online",
"meta": {
"added": [
"v0.7.0"
]
},
"params": [],
"desc": "After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork'
and 'online'
is that fork is emitted when the\nmaster forks a worker, and 'online' is emitted when the worker is running.
cluster.on('online', (worker) => {\n console.log('Yay, the worker responded after it was forked');\n});\n
\n"
},
{
"textRaw": "Event: 'setup'",
"type": "event",
"name": "setup",
"meta": {
"added": [
"v0.7.1"
]
},
"params": [],
"desc": "Emitted every time .setupMaster()
is called.
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.
If accuracy is important, use cluster.settings
.
Calls .disconnect()
on each worker in cluster.workers
.
When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.
\nThe method takes an optional callback argument which will be called when finished.
\nThis can only be called from the master process.
\n" }, { "textRaw": "cluster.fork([env])", "type": "method", "name": "fork", "meta": { "added": [ "v0.6.0" ] }, "signatures": [ { "return": { "textRaw": "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.
\nThis can only be called from the master process.
\n" }, { "textRaw": "cluster.setupMaster([settings])", "type": "method", "name": "setupMaster", "meta": { "added": [ "v0.7.1" ] }, "signatures": [ { "params": [ { "textRaw": "`settings` {Object} ", "options": [ { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "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": "`stdio` {Array} Configures the stdio of forked processes. When this option is provided, it overrides `silent`. ", "name": "stdio", "type": "Array", "desc": "Configures the stdio of forked processes. When this option is provided, it overrides `silent`." } ], "name": "settings", "type": "Object", "optional": true } ] }, { "params": [ { "name": "settings", "optional": true } ] } ], "desc": "setupMaster
is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings
.
Note that:
\n.fork()
and have no\neffect on workers that are already running.setupMaster()
is\nthe env
passed to .fork()
cluster.setupMaster()
is calledExample:
\nconst 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
\nThis can only be called from the master process.
\n" } ], "properties": [ { "textRaw": "`isMaster` {Boolean} ", "type": "Boolean", "name": "isMaster", "meta": { "added": [ "v0.8.1" ] }, "desc": "True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID
. If process.env.NODE_UNIQUE_ID
is\nundefined, then isMaster
is true
.
True if the process is not a master (it is the negation of cluster.isMaster
).
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.
SCHED_RR
is the default on all operating systems except Windows.\nWindows will change to SCHED_RR
once libuv is able to effectively\ndistribute IOCP handles without incurring a large performance hit.
cluster.schedulingPolicy
can also be set through the\nNODE_CLUSTER_SCHED_POLICY
environment variable. Valid\nvalues are "rr"
and "none"
.
After calling .setupMaster()
(or .fork()
) this settings object will contain\nthe settings, including the default values.
This object is not supposed to be changed or set manually, by you.
\n" }, { "textRaw": "`worker` {Object} ", "type": "Object", "name": "worker", "meta": { "added": [ "v0.7.0" ] }, "desc": "A reference to the current worker object. Not available in the master process.
\nconst cluster = require('cluster');\n\nif (cluster.isMaster) {\n console.log('I am master');\n cluster.fork();\n cluster.fork();\n} else if (cluster.isWorker) {\n console.log(`I am worker #${cluster.worker.id}`);\n}\n
\n"
},
{
"textRaw": "`workers` {Object} ",
"type": "Object",
"name": "workers",
"meta": {
"added": [
"v0.7.0"
]
},
"desc": "A hash that stores the active worker objects, keyed by id
field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.
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.
// Go through all workers\nfunction eachWorker(callback) {\n for (const id in cluster.workers) {\n callback(cluster.workers[id]);\n }\n}\neachWorker((worker) => {\n worker.send('big announcement to all workers');\n});\n
\nShould you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.
\nsocket.on('data', (id) => {\n const worker = cluster.workers[id];\n});\n
\n\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.
The module exports two specific components:
\nConsole
class with methods such as console.log()
, console.error()
and\nconsole.warn()
that can be used to write to any Node.js stream.console
instance configured to write to stdout
and stderr
.\nBecause this object is global, it can be used without calling\nrequire('console')
.Example using the global console
:
console.log('hello world');\n// Prints: hello world, to stdout\nconsole.log('hello %s', 'world');\n// Prints: hello world, to stdout\nconsole.error(new Error('Whoops, something bad happened'));\n// Prints: [Error: 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
\nExample using the Console
class:
const out = getStreamSomehow();\nconst err = getStreamSomehow();\nconst myConsole = new console.Console(out, err);\n\nmyConsole.log('hello world');\n// Prints: hello world, to out\nmyConsole.log('hello %s', 'world');\n// Prints: hello world, to out\nmyConsole.error(new Error('Whoops, something bad happened'));\n// Prints: [Error: Whoops, something bad happened], to err\n\nconst name = 'Will Robinson';\nmyConsole.warn(`Danger ${name}! Danger!`);\n// Prints: Danger Will Robinson! Danger!, to err\n
\nWhile 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.
The console functions are usually 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.
\nAdditionally, console functions are blocking when outputting to TTYs\n(terminals) on OS X as a workaround for the OS's very small, 1kb buffer size.\nThis is to prevent interleaving between stdout
and stderr
.
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
:
const Console = require('console').Console;\nconst Console = console.Console;\n
\n",
"methods": [
{
"textRaw": "console.assert(value[, message][, ...args])",
"type": "method",
"name": "assert",
"meta": {
"added": [
"v0.1.101"
]
},
"desc": "A simple assertion test that verifies whether value
is truthy. If it is not,\nan AssertionError
is thrown. If provided, the error message
is formatted\nusing util.format()
and used as the error message.
console.assert(true, 'does nothing');\n// OK\nconsole.assert(false, 'Whoops %s', 'didn\\'t work');\n// AssertionError: Whoops didn't work\n
\nNote: the console.assert()
method is implemented differently in Node.js\nthan the console.assert()
method available in browsers.
Specifically, in browsers, calling console.assert()
with a falsy\nassertion will cause the message
to be printed to the console without\ninterrupting execution of subsequent code. In Node.js, however, a falsy\nassertion will cause an AssertionError
to be thrown.
Functionality approximating that implemented by browsers can be implemented\nby extending Node.js' console
and overriding the console.assert()
method.
In the following example, a simple module is created that extends and overrides\nthe default behavior of console
in Node.js.
'use strict';\n\n// Creates a simple extension of console with a\n// new impl for assert without monkey-patching.\nconst myConsole = Object.create(console, {\n assert: {\n value: function assert(assertion, message, ...args) {\n try {\n console.assert(assertion, message, ...args);\n } catch (err) {\n console.error(err.stack);\n }\n },\n configurable: true,\n enumerable: true,\n writable: true,\n },\n});\n\nmodule.exports = myConsole;\n
\nThis can then be used as a direct replacement for the built in console:
\nconst console = require('./myConsole');\nconsole.assert(false, 'this message will print, but no error thrown');\nconsole.log('this will also print');\n
\n",
"signatures": [
{
"params": [
{
"name": "value"
},
{
"name": "message",
"optional": true
},
{
"name": "...args",
"optional": true
}
]
}
]
},
{
"textRaw": "console.dir(obj[, options])",
"type": "method",
"name": "dir",
"meta": {
"added": [
"v0.1.101"
]
},
"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:
showHidden
- if true
then the object's non-enumerable and symbol\nproperties will be shown too. Defaults to false
.
depth
- tells util.inspect()
how many times to recurse while\nformatting the object. This is useful for inspecting large complicated objects.\nDefaults to 2
. To make it recurse indefinitely, pass null
.
colors
- if true
, then the output will be styled with ANSI color codes.\nDefaults to false
. Colors are customizable; see\ncustomizing util.inspect()
colors.
Prints to stderr
with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to\nutil.format()
).
const code = 5;\nconsole.error('error #%d', code);\n// Prints: error #5, to stderr\nconsole.error('error', code);\n// Prints: error 5, to stderr\n
\nIf formatting elements (e.g. %d
) are not found in the first string then\nutil.inspect()
is called on each argument and the resulting string\nvalues are concatenated. See util.format()
for more information.
The console.info()
function is an alias for console.log()
.
Prints to stdout
with newline. Multiple arguments can be passed, with the\nfirst used as the primary message and all additional used as substitution\nvalues similar to printf(3) (the arguments are all passed to\nutil.format()
).
const count = 5;\nconsole.log('count: %d', count);\n// Prints: count: 5, to stdout\nconsole.log('count:', count);\n// Prints: count: 5, to stdout\n
\nIf formatting elements (e.g. %d
) are not found in the first string then\nutil.inspect()
is called on each argument and the resulting string\nvalues are concatenated. See util.format()
for more information.
Starts a timer that can be used to compute the duration of an operation. Timers\nare identified by a unique label
. Use the same label
when you call\nconsole.timeEnd()
to stop the timer and output the elapsed time in\nmilliseconds to stdout
. Timer durations are accurate to the sub-millisecond.
Stops a timer that was previously started by calling console.time()
and\nprints the result to stdout
:
console.time('100-elements');\nfor (let i = 0; i < 100; i++) {\n ;\n}\nconsole.timeEnd('100-elements');\n// prints 100-elements: 225.438ms\n
\nNote: As of Node.js v6.0.0, console.timeEnd()
deletes the timer to avoid\nleaking it. On older versions, the timer persisted. This allowed\nconsole.timeEnd()
to be called multiple times for the same label. This\nfunctionality was unintended and is no longer supported.
Prints to stderr
the string 'Trace :'
, followed by the util.format()
\nformatted message and stack trace to the current position in the code.
console.trace('Show me');\n// Prints: (stack trace will vary based on where trace is called)\n// Trace: Show me\n// at repl:2:9\n// at REPLServer.defaultEval (repl.js:248:27)\n// at bound (domain.js:287:14)\n// at REPLServer.runBound [as eval] (domain.js:300:12)\n// at REPLServer.<anonymous> (repl.js:412:12)\n// at emitOne (events.js:82:20)\n// at REPLServer.emit (events.js:169:7)\n// at REPLServer.Interface._onLine (readline.js:210:10)\n// at REPLServer.Interface._line (readline.js:549:8)\n// at REPLServer.Interface._ttyWrite (readline.js:826:14)\n
\n",
"signatures": [
{
"params": [
{
"name": "message"
},
{
"name": "...args",
"optional": true
}
]
}
]
},
{
"textRaw": "console.warn([data][, ...args])",
"type": "method",
"name": "warn",
"meta": {
"added": [
"v0.1.100"
]
},
"desc": "The console.warn()
function is an alias for console.error()
.
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
is not passed, warning and error\noutput will be sent to stdout
.
const output = fs.createWriteStream('./stdout.log');\nconst errorOutput = fs.createWriteStream('./stderr.log');\n// custom simple logger\nconst logger = new Console(output, errorOutput);\n// use it like console\nconst count = 5;\nlogger.log('count: %d', count);\n// in stdout.log: count 5\n
\nThe global console
is a special Console
whose output is sent to\nprocess.stdout
and process.stderr
. It is equivalent to calling:
new Console(process.stdout, process.stderr);\n
\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.
Use require('crypto')
to access this module.
const crypto = require('crypto');\n\nconst secret = 'abcdefg';\nconst hash = crypto.createHmac('sha256', secret)\n .update('I love cupcakes')\n .digest('hex');\nconsole.log(hash);\n// Prints:\n// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n
\n",
"modules": [
{
"textRaw": "Determining if crypto support is unavailable",
"name": "determining_if_crypto_support_is_unavailable",
"desc": "It is possible for Node.js to be built without including support for the\ncrypto
module. In such cases, calling require('crypto')
will result in an\nerror being thrown.
let crypto;\ntry {\n crypto = require('crypto');\n} catch (err) {\n console.log('crypto support is disabled!');\n}\n
\n",
"type": "module",
"displayName": "Determining if crypto support is unavailable"
},
{
"textRaw": "`crypto` module methods and properties",
"name": "`crypto`_module_methods_and_properties",
"properties": [
{
"textRaw": "crypto.constants",
"name": "constants",
"meta": {
"added": [
"v6.3.0"
]
},
"desc": "Returns an object containing commonly used constants for crypto and security\nrelated operations. The specific constants currently defined are described in\nCrypto Constants.
\n" }, { "textRaw": "crypto.DEFAULT_ENCODING", "name": "DEFAULT_ENCODING", "meta": { "added": [ "v0.9.3" ] }, "desc": "The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer'
, which makes methods\ndefault to Buffer
objects.
The crypto.DEFAULT_ENCODING
mechanism is provided for backwards compatibility\nwith legacy programs that expect 'latin1'
to be the default encoding.
New applications should expect the default to be 'buffer'
. This property may\nbecome deprecated in a future Node.js release.
Property for checking and controlling whether a FIPS compliant crypto provider is\ncurrently in use. Setting to true requires a FIPS build of Node.js.
\n" } ], "methods": [ { "textRaw": "crypto.createCipher(algorithm, password)", "type": "method", "name": "createCipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "Creates and returns a Cipher
object that uses the given algorithm
and\npassword
.
The algorithm
is dependent on OpenSSL, examples are 'aes192'
, etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms
will display the\navailable cipher algorithms.
The password
is used to derive the cipher key and initialization vector (IV).\nThe value must be either a 'latin1'
encoded string or a Buffer
.
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.
In line with OpenSSL's recommendation to use pbkdf2 instead of\nEVP_BytesToKey
it is recommended that developers derive a key and IV on\ntheir own using crypto.pbkdf2()
and to use crypto.createCipheriv()
\nto create the Cipher
object.
Creates and returns a Cipher
object, with the given algorithm
, key
and\ninitialization vector (iv
).
The algorithm
is dependent on OpenSSL, examples are 'aes192'
, etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms
will display the\navailable cipher algorithms.
The key
is the raw key used by the algorithm
and iv
is an\ninitialization vector. Both arguments must be 'utf8'
encoded strings or\nbuffers.
The crypto.createCredentials()
method is a deprecated function for creating\nand returning a tls.SecureContext
. It should not be used. Replace it with\ntls.createSecureContext()
which has the exact same arguments and return\nvalue.
Returns a tls.SecureContext
, as-if tls.createSecureContext()
had been\ncalled.
Creates and returns a Decipher
object that uses the given algorithm
and\npassword
(key).
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.
In line with OpenSSL's recommendation to use pbkdf2 instead of\nEVP_BytesToKey
it is recommended that developers derive a key and IV on\ntheir own using crypto.pbkdf2()
and to use crypto.createDecipheriv()
\nto create the Decipher
object.
Creates and returns a Decipher
object that uses the given algorithm
, key
\nand initialization vector (iv
).
The algorithm
is dependent on OpenSSL, examples are 'aes192'
, etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms
will display the\navailable cipher algorithms.
The key
is the raw key used by the algorithm
and iv
is an\ninitialization vector. Both arguments must be 'utf8'
encoded strings or\nbuffers.
Creates a DiffieHellman
key exchange object using the supplied prime
and an\noptional specific generator
.
The generator
argument can be a number, string, or Buffer
. If\ngenerator
is not specified, the value 2
is used.
The prime_encoding
and generator_encoding
arguments can be 'latin1'
,\n'hex'
, or 'base64'
.
If prime_encoding
is specified, prime
is expected to be a string; otherwise\na Buffer
is expected.
If generator_encoding
is specified, generator
is expected to be a string;\notherwise either a number or Buffer
is expected.
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.
Creates an Elliptic Curve Diffie-Hellman (ECDH
) key exchange object using a\npredefined curve specified by the curve_name
string. Use\ncrypto.getCurves()
to obtain a list of available curve names. On recent\nOpenSSL releases, openssl ecparam -list_curves
will also display the name\nand description of each available elliptic curve.
Creates and returns a Hash
object that can be used to generate hash digests\nusing the given algorithm
.
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.
Example: generating the sha256 sum of a file
\nconst filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.createReadStream(filename);\ninput.on('readable', () => {\n const data = input.read();\n if (data)\n hash.update(data);\n else {\n console.log(`${hash.digest('hex')} ${filename}`);\n }\n});\n
\n",
"signatures": [
{
"params": [
{
"name": "algorithm"
}
]
}
]
},
{
"textRaw": "crypto.createHmac(algorithm, key)",
"type": "method",
"name": "createHmac",
"meta": {
"added": [
"v0.1.94"
]
},
"desc": "Creates and returns an Hmac
object that uses the given algorithm
and key
.
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.
The key
is the HMAC key used to generate the cryptographic HMAC hash.
Example: generating the sha256 HMAC of a file
\nconst filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.createReadStream(filename);\ninput.on('readable', () => {\n const data = input.read();\n if (data)\n hmac.update(data);\n else {\n console.log(`${hmac.digest('hex')} ${filename}`);\n }\n});\n
\n",
"signatures": [
{
"params": [
{
"name": "algorithm"
},
{
"name": "key"
}
]
}
]
},
{
"textRaw": "crypto.createSign(algorithm)",
"type": "method",
"name": "createSign",
"meta": {
"added": [
"v0.1.92"
]
},
"desc": "Creates and returns a Sign
object that uses the given algorithm
.\nUse crypto.getHashes()
to obtain an array of names of the available\nsigning algorithms.
Creates and returns a Verify
object that uses the given algorithm.\nUse crypto.getHashes()
to obtain an array of names of the available\nsigning algorithms.
Returns an array with the names of the supported cipher algorithms.
\nExample:
\nconst ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "crypto.getCurves()",
"type": "method",
"name": "getCurves",
"meta": {
"added": [
"v2.3.0"
]
},
"desc": "Returns an array with the names of the supported elliptic curves.
\nExample:
\nconst curves = crypto.getCurves();\nconsole.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "crypto.getDiffieHellman(group_name)",
"type": "method",
"name": "getDiffieHellman",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "Creates a predefined DiffieHellman
key exchange object. The\nsupported groups are: 'modp1'
, 'modp2'
, 'modp5'
(defined in\nRFC 2412, but see Caveats) and 'modp14'
, 'modp15'
,\n'modp16'
, 'modp17'
, 'modp18'
(defined in RFC 3526). The\nreturned object mimics the interface of objects created by\ncrypto.createDiffieHellman()
, but will not allow changing\nthe keys (with diffieHellman.setPublicKey()
for example). The\nadvantage of using this method is that the parties do not have to\ngenerate nor exchange a group modulus beforehand, saving both processor\nand communication time.
Example (obtaining a shared secret):
\nconst crypto = require('crypto');\nconst alice = crypto.getDiffieHellman('modp14');\nconst bob = crypto.getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n
\n",
"signatures": [
{
"params": [
{
"name": "group_name"
}
]
}
]
},
{
"textRaw": "crypto.getHashes()",
"type": "method",
"name": "getHashes",
"meta": {
"added": [
"v0.9.3"
]
},
"desc": "Returns an array of the names of the supported hash algorithms,\nsuch as RSA-SHA256
.
Example:
\nconst hashes = crypto.getHashes();\nconsole.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)",
"type": "method",
"name": "pbkdf2",
"meta": {
"added": [
"v0.5.5"
]
},
"desc": "Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest
is\napplied to derive a key of the requested byte length (keylen
) from the\npassword
, salt
and iterations
.
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
.
The iterations
argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.
The salt
should also be as unique as possible. It is recommended that the\nsalts are random and their lengths are greater than 16 bytes. See\nNIST SP 800-132 for details.
Example:
\nconst crypto = require('crypto');\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {\n if (err) throw err;\n console.log(key.toString('hex')); // '3745e48...aa39b34'\n});\n
\nAn array of supported digest functions can be retrieved using\ncrypto.getHashes()
.
Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest
is\napplied to derive a key of the requested byte length (keylen
) from the\npassword
, salt
and iterations
.
If an error occurs an Error will be thrown, otherwise the derived key will be\nreturned as a Buffer
.
The iterations
argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.
The salt
should also be as unique as possible. It is recommended that the\nsalts are random and their lengths are greater than 16 bytes. See\nNIST SP 800-132 for details.
Example:
\nconst crypto = require('crypto');\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...aa39b34'\n
\nAn array of supported digest functions can be retrieved using\ncrypto.getHashes()
.
Decrypts buffer
with private_key
.
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:
key
: {String} - PEM encoded private keypassphrase
: {String} - Optional passphrase for the private keypadding
: An optional padding value, one of the following:crypto.constants.RSA_NO_PADDING
crypto.constants.RSA_PKCS1_PADDING
crypto.constants.RSA_PKCS1_OAEP_PADDING
All paddings are defined in crypto.constants
.
Returns true if a
is equal to b
, without leaking timing information that\nwould allow an attacker to guess one of the values. This is suitable for\ncomparing HMAC digests or secret values like authentication cookies or\ncapability urls.
a
and b
must both be Buffer
s, and they must have the same length.
Note: Use of crypto.timingSafeEqual
does not guarantee that the\nsurrounding code is timing-safe. Care should be taken to ensure that the\nsurrounding code does not introduce timing vulnerabilities.
Encrypts buffer
with private_key
.
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:
key
: {String} - PEM encoded private keypassphrase
: {String} - Optional passphrase for the private keypadding
: An optional padding value, one of the following:crypto.constants.RSA_NO_PADDING
crypto.constants.RSA_PKCS1_PADDING
All paddings are defined in crypto.constants
.
Decrypts buffer
with public_key
.
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:
key
: {String} - PEM encoded public keypassphrase
: {String} - Optional passphrase for the private keypadding
: An optional padding value, one of the following:crypto.constants.RSA_NO_PADDING
crypto.constants.RSA_PKCS1_PADDING
crypto.constants.RSA_PKCS1_OAEP_PADDING
Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
\nAll paddings are defined in crypto.constants
.
Encrypts buffer
with public_key
.
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:
key
: {String} - PEM encoded public keypassphrase
: {String} - Optional passphrase for the private keypadding
: An optional padding value, one of the following:crypto.constants.RSA_NO_PADDING
crypto.constants.RSA_PKCS1_PADDING
crypto.constants.RSA_PKCS1_OAEP_PADDING
Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
\nAll paddings are defined in crypto.constants
.
Generates cryptographically strong pseudo-random data. The size
argument\nis a number indicating the number of bytes to generate.
If a callback
function is provided, the bytes are generated asynchronously\nand the callback
function is invoked with two arguments: err
and buf
.\nIf an error occurs, err
will be an Error object; otherwise it is null. The\nbuf
argument is a Buffer
containing the generated bytes.
// Asynchronous\nconst 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
\nIf the callback
function is not provided, the random bytes are generated\nsynchronously and returned as a Buffer
. An error will be thrown if\nthere is a problem generating the bytes.
// Synchronous\nconst buf = crypto.randomBytes(256);\nconsole.log(\n `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
\nThe 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.
Load and set the engine
for some or all OpenSSL functions (selected by flags).
engine
could be either an id or a path to the engine's shared library.
The optional flags
argument uses ENGINE_METHOD_ALL
by default. The flags
\nis a bit field taking one of or a mix of the following flags (defined in\ncrypto.constants
):
crypto.constants.ENGINE_METHOD_RSA
crypto.constants.ENGINE_METHOD_DSA
crypto.constants.ENGINE_METHOD_DH
crypto.constants.ENGINE_METHOD_RAND
crypto.constants.ENGINE_METHOD_ECDH
crypto.constants.ENGINE_METHOD_ECDSA
crypto.constants.ENGINE_METHOD_CIPHERS
crypto.constants.ENGINE_METHOD_DIGESTS
crypto.constants.ENGINE_METHOD_STORE
crypto.constants.ENGINE_METHOD_PKEY_METHS
crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS
crypto.constants.ENGINE_METHOD_ALL
crypto.constants.ENGINE_METHOD_NONE
The Crypto module was added to Node.js before there was the concept of a\nunified Stream API, and before there were Buffer
objects for handling\nbinary data. As such, the many of the crypto
defined classes have methods not\ntypically found on other Node.js classes that implement the streams\nAPI (e.g. update()
, final()
, or digest()
). Also, many methods accepted\nand returned 'latin1'
encoded strings by default rather than Buffers. This\ndefault was changed after Node.js v0.8 to use Buffer
objects by default\ninstead.
Usage of ECDH
with non-dynamically generated key pairs has been simplified.\nNow, ecdh.setPrivateKey()
can be called with a preselected private key\nand the associated public point (key) will be computed and stored in the object.\nThis allows code to only store and provide the private part of the EC key pair.\necdh.setPrivateKey()
now also validates that the private key is valid for\nthe selected curve.
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.
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.
Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.
\nBased on the recommendations of NIST SP 800-131A:
\nmodp1
, modp2
and modp5
have a key size\nsmaller than 2048 bits and are not recommended.See the reference for other recommendations and details.
\n", "type": "module", "displayName": "Support for weak or compromised algorithms" } ], "type": "module", "displayName": "Notes" }, { "textRaw": "Crypto Constants", "name": "crypto_constants", "desc": "The following constants exported by crypto.constants
apply to various uses of\nthe crypto
, tls
, and https
modules and are generally specific to OpenSSL.
Constant | \nDescription | \n
---|---|
SSL_OP_ALL | \n Applies multiple bug workarounds within OpenSSL. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for\n detail. | \n
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION | \n Allows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. | \n
SSL_OP_CIPHER_SERVER_PREFERENCE | \n Attempts to use the server's preferences instead of the client's when\n selecting a cipher. Behaviour depends on protocol version. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. | \n
SSL_OP_CISCO_ANYCONNECT | \n Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. | \n
SSL_OP_COOKIE_EXCHANGE | \n Instructs OpenSSL to turn on cookie exchange. | \n
SSL_OP_CRYPTOPRO_TLSEXT_BUG | \n Instructs OpenSSL to add server-hello extension from an early version\n of the cryptopro draft. | \n
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS | \n Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d. | \n
SSL_OP_EPHEMERAL_RSA | \n Instructs OpenSSL to always use the tmp_rsa key when performing RSA\n operations. | \n
SSL_OP_LEGACY_SERVER_CONNECT | \n Allows initial connection to servers that do not support RI. | \n
SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER | \n \n |
SSL_OP_MICROSOFT_SESS_ID_BUG | \n \n |
SSL_OP_MSIE_SSLV2_RSA_PADDING | \n Instructs OpenSSL to disable the workaround for a man-in-the-middle\n protocol-version vulnerability in the SSL 2.0 server implementation. | \n
SSL_OP_NETSCAPE_CA_DN_BUG | \n \n |
SSL_OP_NETSCAPE_CHALLENGE_BUG | \n \n |
SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG | \n \n |
SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG | \n \n |
SSL_OP_NO_COMPRESSION | \n Instructs OpenSSL to disable support for SSL/TLS compression. | \n
SSL_OP_NO_QUERY_MTU | \n \n |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | \n Instructs OpenSSL to always start a new session when performing\n renegotiation. | \n
SSL_OP_NO_SSLv2 | \n Instructs OpenSSL to turn off SSL v2 | \n
SSL_OP_NO_SSLv3 | \n Instructs OpenSSL to turn off SSL v3 | \n
SSL_OP_NO_TICKET | \n Instructs OpenSSL to disable use of RFC4507bis tickets. | \n
SSL_OP_NO_TLSv1 | \n Instructs OpenSSL to turn off TLS v1 | \n
SSL_OP_NO_TLSv1_1 | \n Instructs OpenSSL to turn off TLS v1.1 | \n
SSL_OP_NO_TLSv1_2 | \n Instructs OpenSSL to turn off TLS v1.2 | \nSSL_OP_PKCS1_CHECK_1 | \n \n \n |
SSL_OP_PKCS1_CHECK_2 | \n \n |
SSL_OP_SINGLE_DH_USE | \n Instructs OpenSSL to always create a new key when using\n temporary/ephemeral DH parameters. | \n
SSL_OP_SINGLE_ECDH_USE | \n Instructs OpenSSL to always create a new key when using\n temporary/ephemeral ECDH parameters. | \nSSL_OP_SSLEAY_080_CLIENT_DH_BUG | \n \n \n |
SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG | \n \n |
SSL_OP_TLS_BLOCK_PADDING_BUG | \n \n |
SSL_OP_TLS_D5_BUG | \n \n |
SSL_OP_TLS_ROLLBACK_BUG | \n Instructs OpenSSL to disable version rollback attack detection. | \n
Constant | \nDescription | \n
---|---|
ENGINE_METHOD_RSA | \n Limit engine usage to RSA | \n
ENGINE_METHOD_DSA | \n Limit engine usage to DSA | \n
ENGINE_METHOD_DH | \n Limit engine usage to DH | \n
ENGINE_METHOD_RAND | \n Limit engine usage to RAND | \n
ENGINE_METHOD_ECDH | \n Limit engine usage to ECDH | \n
ENGINE_METHOD_ECDSA | \n Limit engine usage to ECDSA | \n
ENGINE_METHOD_CIPHERS | \n Limit engine usage to CIPHERS | \n
ENGINE_METHOD_DIGESTS | \n Limit engine usage to DIGESTS | \n
ENGINE_METHOD_STORE | \n Limit engine usage to STORE | \n
ENGINE_METHOD_PKEY_METHS | \n Limit engine usage to PKEY_METHDS | \n
ENGINE_METHOD_PKEY_ASN1_METHS | \n Limit engine usage to PKEY_ASN1_METHS | \n
ENGINE_METHOD_ALL | \n \n |
ENGINE_METHOD_NONE | \n \n |
Constant | \nDescription | \n
---|---|
DH_CHECK_P_NOT_SAFE_PRIME | \n \n |
DH_CHECK_P_NOT_PRIME | \n \n |
DH_UNABLE_TO_CHECK_GENERATOR | \n \n |
DH_NOT_SUITABLE_GENERATOR | \n \n |
NPN_ENABLED | \n \n |
ALPN_ENABLED | \n \n |
RSA_PKCS1_PADDING | \n \n |
RSA_SSLV23_PADDING | \n \n |
RSA_NO_PADDING | \n \n |
RSA_PKCS1_OAEP_PADDING | \n \n |
RSA_X931_PADDING | \n \n |
RSA_PKCS1_PSS_PADDING | \n \n |
POINT_CONVERSION_COMPRESSED | \n \n |
POINT_CONVERSION_UNCOMPRESSED | \n \n |
POINT_CONVERSION_HYBRID | \n \n |
Constant | \nDescription | \n
---|---|
defaultCoreCipherList | \n Specifies the built-in default cipher list used by Node.js. | \n
defaultCipherList | \n Specifies the active default cipher list used by the current Node.js\n process. | \n
SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and now specified formally as part of HTML5's keygen
element.
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.
Instances of the Certificate
class can be created using the new
keyword\nor by calling crypto.Certificate()
as a function:
const crypto = require('crypto');\n\nconst cert1 = new crypto.Certificate();\nconst cert2 = crypto.Certificate();\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "certificate.exportChallenge(spkac)",
"type": "method",
"name": "exportChallenge",
"meta": {
"added": [
"v0.11.8"
]
},
"desc": "The spkac
data structure includes a public key and a challenge. The\ncertificate.exportChallenge()
returns the challenge component in the\nform of a Node.js Buffer
. The spkac
argument can be either a string\nor a Buffer
.
const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
\n",
"signatures": [
{
"params": [
{
"name": "spkac"
}
]
}
]
},
{
"textRaw": "certificate.exportPublicKey(spkac)",
"type": "method",
"name": "exportPublicKey",
"meta": {
"added": [
"v0.11.8"
]
},
"desc": "The spkac
data structure includes a public key and a challenge. The\ncertificate.exportPublicKey()
returns the public key component in the\nform of a Node.js Buffer
. The spkac
argument can be either a string\nor a Buffer
.
const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
\n",
"signatures": [
{
"params": [
{
"name": "spkac"
}
]
}
]
},
{
"textRaw": "certificate.verifySpkac(spkac)",
"type": "method",
"name": "verifySpkac",
"meta": {
"added": [
"v0.11.8"
]
},
"desc": "Returns true
if the given spkac
data structure is valid, false
otherwise.\nThe spkac
argument must be a Node.js Buffer
.
const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
\n",
"signatures": [
{
"params": [
{
"name": "spkac"
}
]
}
]
}
]
},
{
"textRaw": "Class: Cipher",
"type": "class",
"name": "Cipher",
"meta": {
"added": [
"v0.1.94"
]
},
"desc": "Instances of the Cipher
class are used to encrypt data. The class can be\nused in one of two ways:
cipher.update()
and cipher.final()
methods to produce\nthe encrypted data.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.
Example: Using Cipher
objects as streams:
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nlet encrypted = '';\ncipher.on('readable', () => {\n const data = cipher.read();\n if (data)\n encrypted += data.toString('hex');\n});\ncipher.on('end', () => {\n console.log(encrypted);\n // Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504\n});\n\ncipher.write('some clear text data');\ncipher.end();\n
\nExample: Using Cipher
and piped streams:
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
\nExample: Using the cipher.update()
and cipher.final()
methods:
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nlet encrypted = cipher.update('some clear text data', 'utf8', 'hex');\nencrypted += cipher.final('hex');\nconsole.log(encrypted);\n// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504\n
\n",
"methods": [
{
"textRaw": "cipher.final([output_encoding])",
"type": "method",
"name": "final",
"meta": {
"added": [
"v0.1.94"
]
},
"desc": "Returns any remaining enciphered contents. If output_encoding
\nparameter is one of 'latin1'
, 'base64'
or 'hex'
, a string is returned.\nIf an output_encoding
is not provided, a Buffer
is returned.
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.
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.
Returns this
for method chaining.
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.
The cipher.getAuthTag()
method should only be called after encryption has\nbeen completed using the cipher.final()
method.
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)
.
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.
The cipher.setAutoPadding()
method must be called before cipher.final()
.
Returns this
for method chaining.
Updates the cipher with data
. If the input_encoding
argument is given,\nits value must be one of 'utf8'
, 'ascii'
, or 'latin1'
and the data
\nargument is a string using the specified encoding. If the input_encoding
\nargument is not given, data
must be a Buffer
. If data
is a\nBuffer
then input_encoding
is ignored.
The output_encoding
specifies the output format of the enciphered\ndata, and can be 'latin1'
, 'base64'
or 'hex'
. If the output_encoding
\nis specified, a string using the specified encoding is returned. If no\noutput_encoding
is provided, a Buffer
is returned.
The cipher.update()
method can be called multiple times with new data until\ncipher.final()
is called. Calling cipher.update()
after\ncipher.final()
will result in an error being thrown.
Instances of the Decipher
class are used to decrypt data. The class can be\nused in one of two ways:
decipher.update()
and decipher.final()
methods to\nproduce the unencrypted data.The crypto.createDecipher()
or crypto.createDecipheriv()
methods are\nused to create Decipher
instances. Decipher
objects are not to be created\ndirectly using the new
keyword.
Example: Using Decipher
objects as streams:
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n const data = decipher.read();\n if (data)\n decrypted += data.toString('utf8');\n});\ndecipher.on('end', () => {\n console.log(decrypted);\n // Prints: some clear text data\n});\n\nconst encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n
\nExample: Using Decipher
and piped streams:
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
\nExample: Using the decipher.update()
and decipher.final()
methods:
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nconst encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
\n",
"methods": [
{
"textRaw": "decipher.final([output_encoding])",
"type": "method",
"name": "final",
"meta": {
"added": [
"v0.1.94"
]
},
"desc": "Returns any remaining deciphered contents. If output_encoding
\nparameter is one of 'latin1'
, 'ascii'
or 'utf8'
, a string is returned.\nIf an output_encoding
is not provided, a Buffer
is returned.
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.
When using an authenticated encryption mode (only GCM
is currently\nsupported), the decipher.setAAD()
method sets the value used for the\nadditional authenticated data (AAD) input parameter.
Returns this
for method chaining.
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.
Returns this
for method chaining.
When data has been encrypted without standard block padding, calling\ndecipher.setAutoPadding(false)
will disable automatic padding to prevent\ndecipher.final()
from checking for and removing padding.
Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.
\nThe decipher.setAutoPadding()
method must be called before\ndecipher.update()
.
Returns this
for method chaining.
Updates the decipher with data
. If the input_encoding
argument is given,\nits value must be one of 'latin1'
, 'base64'
, or 'hex'
and the data
\nargument is a string using the specified encoding. If the input_encoding
\nargument is not given, data
must be a Buffer
. If data
is a\nBuffer
then input_encoding
is ignored.
The output_encoding
specifies the output format of the enciphered\ndata, and can be 'latin1'
, 'ascii'
or 'utf8'
. If the output_encoding
\nis specified, a string using the specified encoding is returned. If no\noutput_encoding
is provided, a Buffer
is returned.
The decipher.update()
method can be called multiple times with new data until\ndecipher.final()
is called. Calling decipher.update()
after\ndecipher.final()
will result in an error being thrown.
The DiffieHellman
class is a utility for creating Diffie-Hellman key\nexchanges.
Instances of the DiffieHellman
class can be created using the\ncrypto.createDiffieHellman()
function.
const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n
\n",
"methods": [
{
"textRaw": "diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])",
"type": "method",
"name": "computeSecret",
"meta": {
"added": [
"v0.5.0"
]
},
"desc": "Computes the shared secret using other_public_key
as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified input_encoding
, and secret is\nencoded using specified output_encoding
. Encodings can be\n'latin1'
, 'hex'
, or 'base64'
. If the input_encoding
is not\nprovided, other_public_key
is expected to be a Buffer
.
If output_encoding
is given a string is returned; otherwise, a\nBuffer
is returned.
Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding
. This key should be\ntransferred to the other party. Encoding can be 'latin1'
, 'hex'
,\nor 'base64'
. If encoding
is provided a string is returned; otherwise a\nBuffer
is returned.
Returns the Diffie-Hellman generator in the specified encoding
, which can\nbe 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided a string is\nreturned; otherwise a Buffer
is returned.
Returns the Diffie-Hellman prime in the specified encoding
, which can\nbe 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided a string is\nreturned; otherwise a Buffer
is returned.
Returns the Diffie-Hellman private key in the specified encoding
,\nwhich can be 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided a\nstring is returned; otherwise a Buffer
is returned.
Returns the Diffie-Hellman public key in the specified encoding
, which\ncan be 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided a\nstring is returned; otherwise a Buffer
is returned.
Sets the Diffie-Hellman private key. If the encoding
argument is provided\nand is either 'latin1'
, 'hex'
, or 'base64'
, private_key
is expected\nto be a string. If no encoding
is provided, private_key
is expected\nto be a Buffer
.
Sets the Diffie-Hellman public key. If the encoding
argument is provided\nand is either 'latin1'
, 'hex'
or 'base64'
, public_key
is expected\nto be a string. If no encoding
is provided, public_key
is expected\nto be a Buffer
.
A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman
object.
The following values are valid for this property (as defined in constants
\nmodule):
DH_CHECK_P_NOT_SAFE_PRIME
DH_CHECK_P_NOT_PRIME
DH_UNABLE_TO_CHECK_GENERATOR
DH_NOT_SUITABLE_GENERATOR
The ECDH
class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.
Instances of the ECDH
class can be created using the\ncrypto.createECDH()
function.
const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n // OK\n
\n",
"methods": [
{
"textRaw": "ecdh.computeSecret(other_public_key[, input_encoding][, output_encoding])",
"type": "method",
"name": "computeSecret",
"meta": {
"added": [
"v0.11.14"
]
},
"desc": "Computes the shared secret using other_public_key
as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified input_encoding
, and the returned secret\nis encoded using the specified output_encoding
. Encodings can be\n'latin1'
, 'hex'
, or 'base64'
. If the input_encoding
is not\nprovided, other_public_key
is expected to be a Buffer
.
If output_encoding
is given a string will be returned; otherwise a\nBuffer
is returned.
Generates private and public EC Diffie-Hellman key values, and returns\nthe public key in the specified format
and encoding
. This key should be\ntransferred to the other party.
The format
argument specifies point encoding and can be 'compressed'
or\n'uncompressed'
. If format
is not specified, the point will be returned in\n'uncompressed'
format.
The encoding
argument can be 'latin1'
, 'hex'
, or 'base64'
. If\nencoding
is provided a string is returned; otherwise a Buffer
\nis returned.
Returns the EC Diffie-Hellman private key in the specified encoding
,\nwhich can be 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided\na string is returned; otherwise a Buffer
is returned.
Returns the EC Diffie-Hellman public key in the specified encoding
and\nformat
.
The format
argument specifies point encoding and can be 'compressed'
or\n'uncompressed'
. If format
is not specified the point will be returned in\n'uncompressed'
format.
The encoding
argument can be 'latin1'
, 'hex'
, or 'base64'
. If\nencoding
is specified, a string is returned; otherwise a Buffer
is\nreturned.
Sets the EC Diffie-Hellman private key. The encoding
can be 'latin1'
,\n'hex'
or 'base64'
. If encoding
is provided, private_key
is expected\nto be a string; otherwise private_key
is expected to be a Buffer
. If\nprivate_key
is not valid for the curve specified when the ECDH
object was\ncreated, an error is thrown. Upon setting the private key, the associated\npublic point (key) is also generated and set in the ECDH object.
Sets the EC Diffie-Hellman public key. Key encoding can be 'latin1'
,\n'hex'
or 'base64'
. If encoding
is provided public_key
is expected to\nbe a string; otherwise a Buffer
is expected.
Note that there is not normally a reason to call this method because ECDH
\nonly requires a private key and the other party's public key to compute the\nshared secret. Typically either ecdh.generateKeys()
or\necdh.setPrivateKey()
will be called. The ecdh.setPrivateKey()
method\nattempts to generate the public point/key associated with the private key being\nset.
Example (obtaining a shared secret):
\nconst crypto = require('crypto');\nconst alice = crypto.createECDH('secp256k1');\nconst bob = crypto.createECDH('secp256k1');\n\n// Note: This is a shortcut way to specify one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n crypto.createHash('sha256').update('alice', 'utf8').digest()\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n
\n",
"signatures": [
{
"params": [
{
"name": "public_key"
},
{
"name": "encoding",
"optional": true
}
]
}
]
}
]
},
{
"textRaw": "Class: Hash",
"type": "class",
"name": "Hash",
"meta": {
"added": [
"v0.1.92"
]
},
"desc": "The Hash
class is a utility for creating hash digests of data. It can be\nused in one of two ways:
hash.update()
and hash.digest()
methods to produce the\ncomputed hash.The crypto.createHash()
method is used to create Hash
instances. Hash
\nobjects are not to be created directly using the new
keyword.
Example: Using Hash
objects as streams:
const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.on('readable', () => {\n const data = hash.read();\n if (data)\n console.log(data.toString('hex'));\n // Prints:\n // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n});\n\nhash.write('some data to hash');\nhash.end();\n
\nExample: Using Hash
and piped streams:
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
\nExample: Using the hash.update()
and hash.digest()
methods:
const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
\n",
"methods": [
{
"textRaw": "hash.digest([encoding])",
"type": "method",
"name": "digest",
"meta": {
"added": [
"v0.1.92"
]
},
"desc": "Calculates the digest of all of the data passed to be hashed (using the\nhash.update()
method). The encoding
can be 'hex'
, 'latin1'
or\n'base64'
. If encoding
is provided a string will be returned; otherwise\na Buffer
is returned.
The Hash
object can not be used again after hash.digest()
method has been\ncalled. Multiple calls will cause an error to be thrown.
Updates the hash content with the given data
, the encoding of which\nis given in input_encoding
and can be 'utf8'
, 'ascii'
or\n'latin1'
. If encoding
is not provided, and the data
is a string, an\nencoding of 'utf8'
is enforced. If data
is a Buffer
then\ninput_encoding
is ignored.
This can be called many times with new data as it is streamed.
\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "meta": { "added": [ "v0.1.94" ] }, "desc": "The Hmac
Class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:
hmac.update()
and hmac.digest()
methods to produce the\ncomputed HMAC digest.The crypto.createHmac()
method is used to create Hmac
instances. Hmac
\nobjects are not to be created directly using the new
keyword.
Example: Using Hmac
objects as streams:
const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n const data = hmac.read();\n if (data)\n console.log(data.toString('hex'));\n // Prints:\n // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n});\n\nhmac.write('some data to hash');\nhmac.end();\n
\nExample: Using Hmac
and piped streams:
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
\nExample: Using the hmac.update()
and hmac.digest()
methods:
const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n
\n",
"methods": [
{
"textRaw": "hmac.digest([encoding])",
"type": "method",
"name": "digest",
"meta": {
"added": [
"v0.1.94"
]
},
"desc": "Calculates the HMAC digest of all of the data passed using hmac.update()
.\nThe encoding
can be 'hex'
, 'latin1'
or 'base64'
. If encoding
is\nprovided a string is returned; otherwise a Buffer
is returned;
The Hmac
object can not be used again after hmac.digest()
has been\ncalled. Multiple calls to hmac.digest()
will result in an error being thrown.
Updates the Hmac
content with the given data
, the encoding of which\nis given in input_encoding
and can be 'utf8'
, 'ascii'
or\n'latin1'
. If encoding
is not provided, and the data
is a string, an\nencoding of 'utf8'
is enforced. If data
is a Buffer
then\ninput_encoding
is ignored.
This can be called many times with new data as it is streamed.
\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "meta": { "added": [ "v0.1.92" ] }, "desc": "The Sign
Class is a utility for generating signatures. It can be used in one\nof two ways:
sign.sign()
method is used to generate and return the signature, orsign.update()
and sign.sign()
methods to produce the\nsignature.The crypto.createSign()
method is used to create Sign
instances. Sign
\nobjects are not to be created directly using the new
keyword.
Example: Using Sign
objects as streams:
const crypto = require('crypto');\nconst sign = crypto.createSign('RSA-SHA256');\n\nsign.write('some data to sign');\nsign.end();\n\nconst privateKey = getPrivateKeySomehow();\nconsole.log(sign.sign(privateKey, 'hex'));\n// Prints: the calculated signature\n
\nExample: Using the sign.update()
and sign.sign()
methods:
const crypto = require('crypto');\nconst sign = crypto.createSign('RSA-SHA256');\n\nsign.update('some data to sign');\n\nconst privateKey = getPrivateKeySomehow();\nconsole.log(sign.sign(privateKey, 'hex'));\n// Prints: the calculated signature\n
\nA Sign
instance can also be created by just passing in the digest\nalgorithm name, in which case OpenSSL will infer the full signature algorithm\nfrom the type of the PEM-formatted private key, including algorithms that\ndo not have directly exposed name constants, e.g. 'ecdsa-with-SHA256'.
Example: signing using ECDSA with SHA256
\nconst crypto = require('crypto');\nconst sign = crypto.createSign('sha256');\n\nsign.update('some data to sign');\n\nconst privateKey =\n`-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\nAwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\npQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n-----END EC PRIVATE KEY-----`;\n\nconsole.log(sign.sign(privateKey).toString('hex'));\n
\n",
"methods": [
{
"textRaw": "sign.sign(private_key[, output_format])",
"type": "method",
"name": "sign",
"meta": {
"added": [
"v0.1.92"
]
},
"desc": "Calculates the signature on all the data passed through using either\nsign.update()
or sign.write()
.
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:
key
: {String} - PEM encoded private keypassphrase
: {String} - passphrase for the private keyThe output_format
can specify one of 'latin1'
, 'hex'
or 'base64'
. If\noutput_format
is provided a string is returned; otherwise a Buffer
is\nreturned.
The Sign
object can not be again used after sign.sign()
method has been\ncalled. Multiple calls to sign.sign()
will result in an error being thrown.
Updates the Sign
content with the given data
, the encoding of which\nis given in input_encoding
and can be 'utf8'
, 'ascii'
or\n'latin1'
. If encoding
is not provided, and the data
is a string, an\nencoding of 'utf8'
is enforced. If data
is a Buffer
then\ninput_encoding
is ignored.
This can be called many times with new data as it is streamed.
\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "meta": { "added": [ "v0.1.92" ] }, "desc": "The Verify
class is a utility for verifying signatures. It can be used in one\nof two ways:
verify.update()
and verify.verify()
methods to verify\nthe signature.The crypto.createVerify()
method is used to create Verify
instances.\nVerify
objects are not to be created directly using the new
keyword.
Example: Using Verify
objects as streams:
const crypto = require('crypto');\nconst verify = crypto.createVerify('RSA-SHA256');\n\nverify.write('some data to sign');\nverify.end();\n\nconst publicKey = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true or false\n
\nExample: Using the verify.update()
and verify.verify()
methods:
const crypto = require('crypto');\nconst verify = crypto.createVerify('RSA-SHA256');\n\nverify.update('some data to sign');\n\nconst publicKey = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true or false\n
\n",
"methods": [
{
"textRaw": "verifier.update(data[, input_encoding])",
"type": "method",
"name": "update",
"meta": {
"added": [
"v0.1.92"
]
},
"desc": "Updates the Verify
content with the given data
, the encoding of which\nis given in input_encoding
and can be 'utf8'
, 'ascii'
or\n'latin1'
. If encoding
is not provided, and the data
is a string, an\nencoding of 'utf8'
is enforced. If data
is a Buffer
then\ninput_encoding
is ignored.
This can be called many times with new data as it is streamed.
\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] }, { "textRaw": "verifier.verify(object, signature[, signature_format])", "type": "method", "name": "verify", "meta": { "added": [ "v0.1.92" ] }, "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 'latin1'
, 'hex'
or 'base64'
.\nIf a signature_format
is specified, the signature
is expected to be a\nstring; otherwise signature
is expected to be a Buffer
.
Returns true
or false
depending on the validity of the signature for\nthe data and public key.
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.
The dgram
module provides an implementation of UDP Datagram sockets.
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
\n",
"classes": [
{
"textRaw": "Class: dgram.Socket",
"type": "class",
"name": "dgram.Socket",
"meta": {
"added": [
"v0.1.99"
]
},
"desc": "The dgram.Socket
object is an EventEmitter
that encapsulates the\ndatagram functionality.
New instances of dgram.Socket
are created using dgram.createSocket()
.\nThe new
keyword is not to be used to create dgram.Socket
instances.
The 'close'
event is emitted after a socket is closed with close()
.\nOnce triggered, no new 'message'
events will be emitted on this socket.
The 'error'
event is emitted whenever any error occurs. The event handler\nfunction is passed a single Error object.
The 'listening'
event is emitted whenever a socket begins listening for\ndatagram messages. This occurs as soon as UDP sockets are created.
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
.
msg
{Buffer} - The messagerinfo
{Object} - Remote address informationaddress
{String} The sender addressfamily
{String} The address family ('IPv4'
or 'IPv6'
)port
{Number} The sender portsize
{Number} The message sizeTells the kernel to join a multicast group at the given multicastAddress
and\nmulticastInterface
using the IP_ADD_MEMBERSHIP
socket option. If the\nmulticastInterface
argument is not specified, the operating system will choose\none interface and will add membership to it. To add membership to every\navailable interface, call addMembership
multiple times, once per interface.
Returns an object containing the address information for a socket.\nFor UDP sockets, this object will contain address
, family
and port
\nproperties.
For UDP sockets, causes the dgram.Socket
to listen for datagram\nmessages on a named port
and optional address
. If port
is not\nspecified or is 0
, the operating system will attempt to bind to a\nrandom port. If address
is not specified, the operating system will\nattempt to listen on all addresses. Once binding is complete, a\n'listening'
event is emitted and the optional callback
function is\ncalled.
Note that specifying both a 'listening'
event listener and passing a\ncallback
to the socket.bind()
method is not harmful but not very\nuseful.
A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.
\nIf binding fails, an 'error'
event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error
may be thrown.
Example of a UDP server listening on port 41234:
\nconst 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
\n"
},
{
"textRaw": "socket.bind(options[, callback])",
"type": "method",
"name": "bind",
"meta": {
"added": [
"v0.11.14"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} - Required. Supports the following properties: ",
"options": [
{
"textRaw": "`port` {Number} - Optional. ",
"name": "port",
"type": "Number",
"desc": "Optional."
},
{
"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\nmessages on a named port
and optional address
that are passed as\nproperties of an options
object passed as the first argument. If\nport
is not specified or is 0
, the operating system will attempt\nto bind to a random port. If address
is not specified, the operating\nsystem will attempt to listen on all addresses. Once binding is\ncomplete, a 'listening'
event is emitted and the optional callback
\nfunction is called.
Note that specifying both a 'listening'
event listener and passing a\ncallback
to the socket.bind()
method is not harmful but not very\nuseful.
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.
A bound datagram socket keeps the Node.js process running to receive\ndatagram messages.
\nIf binding fails, an 'error'
event is generated. In rare case (e.g.\nattempting to bind with a closed socket), an Error
may be thrown.
An example socket listening on an exclusive port is shown below.
\nsocket.bind({\n address: 'localhost',\n port: 8000,\n exclusive: true\n});\n
\n"
},
{
"textRaw": "socket.close([callback])",
"type": "method",
"name": "close",
"meta": {
"added": [
"v0.1.99"
]
},
"desc": "Close the underlying socket and stop listening for data on it. If a callback is\nprovided, it is added as a listener for the 'close'
event.
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.
If multicastInterface
is not specified, the operating system will attempt to\ndrop membership on all valid interfaces.
Broadcasts a datagram on the socket. The destination port
and address
must\nbe specified.
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.
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.
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.)
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.
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.
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
.
Example of sending a UDP packet to a random port on localhost
;
const dgram = require('dgram');\nconst message = Buffer.from('Some bytes');\nconst client = dgram.createSocket('udp4');\nclient.send(message, 41234, 'localhost', (err) => {\n client.close();\n});\n
\nExample of sending a UDP packet composed of multiple buffers to a random port on localhost
;
const dgram = require('dgram');\nconst buf1 = Buffer.from('Some ');\nconst buf2 = Buffer.from('bytes');\nconst client = dgram.createSocket('udp4');\nclient.send([buf1, buf2], 41234, 'localhost', (err) => {\n client.close();\n});\n
\nSending multiple buffers might be faster or slower depending on your\napplication and operating system: benchmark it. Usually it is faster.
\nA Note about UDP datagram size
\nThe maximum size of an IPv4/v6
datagram depends on the MTU
\n(Maximum Transmission Unit) and on the Payload Length
field size.
The Payload Length
field is 16 bits
wide, which means that a normal\npayload exceed 64K octets including the internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagram\nmessages are impractical for most hosts and networks.
The MTU
is the largest size a given link layer technology can support for\ndatagram messages. For any link, IPv4
mandates a minimum MTU
of 68
\noctets, while the recommended MTU
for IPv4 is 576
(typically recommended\nas the MTU
for dial-up type applications), whether they arrive whole or in\nfragments.
For IPv6
, the minimum MTU
is 1280
octets, however, the mandatory minimum\nfragment reassembly buffer size is 1500
octets. The value of 68
octets is\nvery small, since most current link layer technologies, like Ethernet, have a\nminimum MTU
of 1500
.
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.
Sets or clears the SO_BROADCAST
socket option. When set to true
, UDP\npackets may be sent to a local interface's broadcast address.
Sets or clears the IP_MULTICAST_LOOP
socket option. When set to true
,\nmulticast packets will also be received on the local interface.
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.
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.
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.
The argument to socket.setTTL()
is a number of hops between 1 and 255.\nThe default on most systems is 64 but can vary.
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.
Calling socket.ref()
multiples times will have no additional effect.
The socket.ref()
method returns a reference to the socket so calls can be\nchained.
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.
Calling socket.unref()
multiple times will have no addition effect.
The socket.unref()
method returns a reference to the socket so calls can be\nchained.
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:
const s = dgram.createSocket('udp4');\ns.bind(1234);\ns.addMembership('224.0.0.114');\n
\nMust be changed to pass a callback function to the dgram.Socket#bind()
\nfunction:
const s = dgram.createSocket('udp4');\ns.bind(1234, () => {\n s.addMembership('224.0.0.114');\n});\n
\n",
"type": "module",
"displayName": "Change to asynchronous `socket.bind()` behavior"
}
]
}
],
"modules": [
{
"textRaw": "`dgram` module functions",
"name": "`dgram`_module_functions",
"methods": [
{
"textRaw": "dgram.createSocket(options[, callback])",
"type": "method",
"name": "createSocket",
"meta": {
"added": [
"v0.11.13"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {dgram.Socket} ",
"name": "return",
"type": "dgram.Socket"
},
"params": [
{
"textRaw": "`options` {Object} ",
"name": "options",
"type": "Object"
},
{
"textRaw": "`callback` {Function} Attached as a listener to `'message'` events. ",
"name": "callback",
"type": "Function",
"desc": "Attached as a listener to `'message'` events.",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Creates a dgram.Socket
object. The options
argument is an object that\nshould contain a type
field of either udp4
or udp6
and an optional\nboolean reuseAddr
field.
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.
Once the socket is created, calling socket.bind()
will instruct the\nsocket to begin listening for datagram messages. When address
and port
are\nnot passed to socket.bind()
the method will bind the socket to the "all\ninterfaces" address on a random port (it does the right thing for both udp4
\nand udp6
sockets). The bound address and port can be retrieved using\nsocket.address().address
and socket.address().port
.
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.
Once the socket is created, calling socket.bind()
will instruct the\nsocket to begin listening for datagram messages. When address
and port
are\nnot passed to socket.bind()
the method will bind the socket to the "all\ninterfaces" address on a random port (it does the right thing for both udp4
\nand udp6
sockets). The bound address and port can be retrieved using\nsocket.address().address
and socket.address().port
.
The dns
module contains functions belonging to two different categories:
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()
.
For example, looking up nodejs.org
.
const dns = require('dns');\n\ndns.lookup('nodejs.org', (err, addresses, family) => {\n console.log('addresses:', addresses);\n});\n
\n2) Functions that connect to an actual DNS server to perform name resolution,\nand that always use the network to perform DNS queries. This category\ncontains all functions in the dns
module except dns.lookup()
. These\nfunctions do not use the same set of configuration files used by\ndns.lookup()
(e.g. /etc/hosts
). These functions should be used by\ndevelopers who do not want to use the underlying operating system's facilities\nfor name resolution, and instead want to always perform DNS queries.
Below is an example that resolves 'nodejs.org'
then reverse resolves the IP\naddresses that are returned.
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
\nThere are subtle consequences in choosing one over the other, please consult\nthe Implementation considerations section for more information.
\n", "methods": [ { "textRaw": "dns.getServers()", "type": "method", "name": "getServers", "meta": { "added": [ "v0.11.3" ] }, "desc": "Returns an array of IP address strings that are being used for name\nresolution.
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "dns.lookup(hostname[, options], callback)", "type": "method", "name": "lookup", "meta": { "added": [ "v0.1.90" ] }, "desc": "Resolves a hostname (e.g. 'nodejs.org'
) into the first found A (IPv4) or\nAAAA (IPv6) record. options
can be an object or integer. If options
is\nnot provided, then IPv4 and IPv6 addresses are both valid. If options
is\nan integer, then it must be 4
or 6
.
Alternatively, options
can be an object containing these properties:
family
{Number} - The record family. If present, must be the integer\n4
or 6
. If not provided, both IP v4 and v6 addresses are accepted.hints
: {Number} - If present, it should be one or more of the supported\ngetaddrinfo
flags. If hints
is not provided, then no flags are passed to\ngetaddrinfo
. Multiple flags can be passed through hints
by bitwise\nOR
ing their values.\nSee supported getaddrinfo
flags for more information on supported\nflags.all
: {Boolean} - When true
, the callback returns all resolved addresses\nin an array, otherwise returns a single address. Defaults to false
.All properties are optional. An example usage of options is shown below.
\n{\n family: 4,\n hints: dns.ADDRCONFIG | dns.V4MAPPED,\n all: false\n}\n
\nThe 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
).
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
.
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.
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()
.
The following flags can be passed as hints to dns.lookup()
.
dns.ADDRCONFIG
: Returned address types are determined by the types\nof addresses supported by the current system. For example, IPv4 addresses\nare only returned if the current system has at least one IPv4 address\nconfigured. Loopback addresses are not considered.dns.V4MAPPED
: If the IPv6 family was specified, but no IPv6 addresses were\nfound, then return IPv4 mapped IPv6 addresses. Note that it is not supported\non some operating systems (e.g FreeBSD 10.1).Resolves the given address
and port
into a hostname and service using\nthe operating system's underlying getnameinfo
implementation.
If address
is not a valid IP address, a TypeError
will be thrown.\nThe port
will be coerced to a number. If it is not a legal port, a TypeError
\nwill be thrown.
The callback has arguments (err, hostname, service)
. The hostname
and\nservice
arguments are strings (e.g. 'localhost'
and 'http'
respectively).
On error, err
is an Error
object, where err.code
is the error code.
const dns = require('dns');\ndns.lookupService('127.0.0.1', 22, (err, hostname, service) => {\n console.log(hostname, service);\n // Prints: localhost ssh\n});\n
\n",
"signatures": [
{
"params": [
{
"name": "address"
},
{
"name": "port"
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "dns.resolve(hostname[, rrtype], callback)",
"type": "method",
"name": "resolve",
"meta": {
"added": [
"v0.1.27"
]
},
"desc": "Uses the DNS protocol to resolve a hostname (e.g. 'nodejs.org'
) into an\narray of the record types specified by rrtype
.
Valid values for rrtype
are:
'A'
- IPV4 addresses, default'AAAA'
- IPV6 addresses'MX'
- mail exchange records'TXT'
- text records'SRV'
- SRV records'PTR'
- PTR records'NS'
- name server records'CNAME'
- canonical name records'SOA'
- start of authority record'NAPTR'
- name authority pointer recordThe callback
function has arguments (err, addresses)
. When successful,\naddresses
will be an array, except when resolving an SOA record which returns\nan object structured in the same manner as one returned by the\ndns.resolveSoa()
method. The type of each item in addresses
is\ndetermined by the record type, and described in the documentation for the\ncorresponding lookup methods.
On error, err
is an Error
object, where err.code
is\none of the error codes listed here.
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']
).
hostname
{String} Hostname to resolve.options
{Object}ttl
{Boolean} Retrieve the Time-To-Live value (TTL) of each record.\nThe callback receives an array of { address: '1.2.3.4', ttl: 60 }
objects\nrather than an array of strings. The TTL is expressed in seconds.callback
{Function} An (err, result)
callback function.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.
hostname
{String} Hostname to resolve.options
{Object}ttl
{Boolean} Retrieve the Time-To-Live value (TTL) of each record.\nThe callback receives an array of { address: '0:1:2:3:4:5:6:7', ttl: 60 }
\nobjects rather than an array of strings. The TTL is expressed in seconds.callback
{Function} An (err, result)
callback function.Uses the DNS protocol to resolve CNAME
records for the hostname
. The\naddresses
argument passed to the callback
function\nwill contain an array of canonical name records available for the hostname
\n(e.g. ['bar.example.com']
).
Uses the DNS protocol to resolve mail exchange records (MX
records) for the\nhostname
. The addresses
argument passed to the callback
function will\ncontain an array of objects containing both a priority
and exchange
\nproperty (e.g. [{priority: 10, exchange: 'mx.example.com'}, ...]
).
Uses the DNS protocol to resolve regular expression based records (NAPTR
\nrecords) for the hostname
. The callback
function has arguments\n(err, addresses)
. The addresses
argument passed to the callback
function\nwill contain an array of objects with the following properties:
flags
service
regexp
replacement
order
preference
For example:
\n{\n flags: 's',\n service: 'SIP+D2U',\n regexp: '',\n replacement: '_sip._udp.example.com',\n order: 30,\n preference: 100\n}\n
\n",
"signatures": [
{
"params": [
{
"name": "hostname"
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "dns.resolveNs(hostname, callback)",
"type": "method",
"name": "resolveNs",
"meta": {
"added": [
"v0.1.90"
]
},
"desc": "Uses the DNS protocol to resolve name server records (NS
records) for the\nhostname
. The addresses
argument passed to the callback
function will\ncontain an array of name server records available for hostname
\n(e.g. ['ns1.example.com', 'ns2.example.com']
).
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:
nsname
hostmaster
serial
refresh
retry
expire
minttl
{\n nsname: 'ns.example.com',\n hostmaster: 'root.example.com',\n serial: 2013101809,\n refresh: 10000,\n retry: 2400,\n expire: 604800,\n minttl: 3600\n}\n
\n",
"signatures": [
{
"params": [
{
"name": "hostname"
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "dns.resolveSrv(hostname, callback)",
"type": "method",
"name": "resolveSrv",
"meta": {
"added": [
"v0.1.27"
]
},
"desc": "Uses the DNS protocol to resolve service records (SRV
records) for the\nhostname
. The addresses
argument passed to the callback
function will\nbe an array of objects with the following properties:
priority
weight
port
name
{\n priority: 10,\n weight: 5,\n port: 21223,\n name: 'service.example.com'\n}\n
\n",
"signatures": [
{
"params": [
{
"name": "hostname"
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "dns.resolvePtr(hostname, callback)",
"type": "method",
"name": "resolvePtr",
"meta": {
"added": [
"v6.0.0"
]
},
"desc": "Uses the DNS protocol to resolve pointer records (PTR
records) for the\nhostname
. The addresses
argument passed to the callback
function will\nbe an array of strings containing the reply records.
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-dimensional array of the text records available for hostname
(e.g.,\n[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]
). Each sub-array contains TXT chunks of\none record. Depending on the use case, these could be either joined together or\ntreated separately.
Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an\narray of hostnames.
\nThe callback
function has arguments (err, hostnames)
, where hostnames
\nis an array of resolved hostnames for the given ip
.
On error, err
is an Error
object, where err.code
is\none of the DNS error codes.
Sets the IP addresses of the servers to be used when resolving. The servers
\nargument is an array of IPv4 or IPv6 addresses.
If a port specified on the address it will be removed.
\nAn error will be thrown if an invalid address is provided.
\nThe dns.setServers()
method must not be called while a DNS query is in\nprogress.
Each DNS query can return one of the following error codes:
\ndns.NODATA
: DNS server returned answer with no data.dns.FORMERR
: DNS server claims query was misformatted.dns.SERVFAIL
: DNS server returned general failure.dns.NOTFOUND
: Domain name not found.dns.NOTIMP
: DNS server does not implement requested operation.dns.REFUSED
: DNS server refused query.dns.BADQUERY
: Misformatted DNS query.dns.BADNAME
: Misformatted hostname.dns.BADFAMILY
: Unsupported address family.dns.BADRESP
: Misformatted DNS reply.dns.CONNREFUSED
: Could not contact DNS servers.dns.TIMEOUT
: Timeout while contacting DNS servers.dns.EOF
: End of file.dns.FILE
: Error reading file.dns.NOMEM
: Out of memory.dns.DESTRUCTION
: Channel is being destroyed.dns.BADSTR
: Misformatted string.dns.BADFLAGS
: Illegal flags specified.dns.NONAME
: Given hostname is not numeric.dns.BADHINTS
: Illegal hints flags specified.dns.NOTINITIALIZED
: c-ares library initialization not yet performed.dns.LOADIPHLPAPI
: Error loading iphlpapi.dll.dns.ADDRGETNETWORKPARAMS
: Could not find GetNetworkParams function.dns.CANCELLED
: DNS query cancelled.Although dns.lookup()
and the various dns.resolve*()/dns.reverse()
\nfunctions have the same goal of associating a network name with a network\naddress (or vice versa), their behavior is quite different. These differences\ncan have subtle but significant consequences on the behavior of Node.js\nprograms.
Under the hood, dns.lookup()
uses the same operating system facilities\nas most other programs. For instance, dns.lookup()
will almost always\nresolve a given name the same way as the ping
command. On most POSIX-like\noperating systems, the behavior of the dns.lookup()
function can be\nmodified by changing settings in nsswitch.conf(5) and/or resolv.conf(5),\nbut note that changing these files will change the behavior of all other\nprograms running on the same operating system.
Though the call to dns.lookup()
will be asynchronous from JavaScript's\nperspective, it is implemented as a synchronous call to getaddrinfo(3) that\nruns on libuv's threadpool. Because libuv's threadpool has a fixed size, it\nmeans that if for whatever reason the call to getaddrinfo(3) takes a long\ntime, other operations that could run on libuv's threadpool (such as filesystem\noperations) will experience degraded performance. In order to mitigate this\nissue, one potential solution is to increase the size of libuv's threadpool by\nsetting the 'UV_THREADPOOL_SIZE'
environment variable to a value greater than\n4
(its current default value). For more information on libuv's threadpool, see\nthe official libuv documentation.
These functions are implemented quite differently than dns.lookup()
. They\ndo not use getaddrinfo(3) and they always perform a DNS query on the\nnetwork. This network communication is always done asynchronously, and does not\nuse libuv's threadpool.
As a result, these functions cannot have the same negative impact on other\nprocessing that happens on libuv's threadpool that dns.lookup()
can have.
They do not use the same set of configuration files than what dns.lookup()
\nuses. For instance, they do not use the configuration from /etc/hosts
.
This module is pending deprecation. Once a replacement API has been\nfinalized, this module will be fully deprecated. Most 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.
\nDomains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an 'error'
event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException')
handler, or causing the program to\nexit immediately with an error code.
Domain error handlers are not a substitute for closing down your\nprocess when an error occurs.
\nBy the very nature of how throw
works in JavaScript, there is almost\nnever any way to safely "pick up where you left off", without leaking\nreferences, or creating some other sort of undefined brittle state.
The safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, you might have many\nconnections open, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.
\nThe better approach is to send an error response to the request that\ntriggered the error, while letting the others finish in their normal\ntime, and stop listening for new requests in that worker.
\nIn this way, domain
usage goes hand-in-hand with the cluster module,\nsince the 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.
For example, this is not a good idea:
\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
\nBy using the context of a domain, and the resilience of separating our\nprogram into multiple worker processes, we can react more\nappropriately, and handle errors with much greater safety.
\n// Much better!\n\nconst cluster = require('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 is not important. Just an example routing thing.\n// You'd put your fancy application logic here.\nfunction handleRequest(req, res) {\n switch(req.url) {\n case '/error':\n // We do some async stuff, and then...\n setTimeout(() => {\n // Whoops!\n flerb.bark();\n });\n break;\n default:\n res.end('ok');\n }\n}\n
\n"
},
{
"textRaw": "Additions to Error objects",
"name": "Additions to Error objects",
"type": "misc",
"desc": "Any time an Error
object is routed through a domain, a few extra fields\nare added to it.
error.domain
The domain that first handled the error.error.domainEmitter
The event emitter that emitted an 'error'
event\nwith the error object.error.domainBound
The callback function which was bound to the\ndomain, and passed an error as its first argument.error.domainThrown
A boolean indicating whether the error was\nthrown, emitted, or passed to a bound callback function.If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.
\nAdditionally, 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.
\nIn 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.
\nIf you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them.
\nImplicit 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.
Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.
\nFor example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.
\nThat is possible via explicit binding.
\nFor example:
\n// create a top-level domain for the server\nconst domain = require('domain');\nconst http = require('http');\nconst serverDomain = domain.create();\n\nserverDomain.run(() => {\n // server is created in the scope of serverDomain\n http.createServer((req, res) => {\n // req and res are also created in the scope of serverDomain\n // however, we'd prefer to have a separate domain for each request.\n // create it first thing, and add req and res to it.\n 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
\n"
}
],
"methods": [
{
"textRaw": "domain.create()",
"type": "method",
"name": "create",
"signatures": [
{
"return": {
"textRaw": "Returns: {Domain} ",
"name": "return",
"type": "Domain"
},
"params": []
},
{
"params": []
}
],
"desc": "Returns a new Domain object.
\n" } ], "classes": [ { "textRaw": "Class: Domain", "type": "class", "name": "Domain", "desc": "The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.
\nDomain is a child class of EventEmitter
. To handle the errors that it\ncatches, listen to its 'error'
event.
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.
\nThis is the most basic way to use a domain.
\nExample:
\nconst 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
\nIn this example, the d.on('error')
handler will be triggered, rather\nthan crashing the program.
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.
This also works with timers that are returned from setInterval()
and\nsetTimeout()
. If their callback function throws, it will be caught by\nthe domain 'error' handler.
If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.
\n" }, { "textRaw": "domain.remove(emitter)", "type": "method", "name": "remove", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter|Timer} emitter or timer to be removed from the domain ", "name": "emitter", "type": "EventEmitter|Timer", "desc": "emitter or timer to be removed from the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "The opposite of domain.add(emitter)
. Removes domain handling from the\nspecified emitter.
The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's 'error'
event.
const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n fs.readFile(filename, 'utf8', d.bind((er, data) => {\n // if this throws, it will also be passed to the domain\n return cb(er, data ? JSON.parse(data) : null);\n }));\n}\n\nd.on('error', (er) => {\n // an error occurred somewhere.\n // if we throw it now, it will crash the program\n // with the normal line number and stack message.\n});\n
\n"
},
{
"textRaw": "domain.intercept(callback)",
"type": "method",
"name": "intercept",
"signatures": [
{
"return": {
"textRaw": "Returns: {Function} The intercepted function ",
"name": "return",
"type": "Function",
"desc": "The intercepted function"
},
"params": [
{
"textRaw": "`callback` {Function} The callback function ",
"name": "callback",
"type": "Function",
"desc": "The callback function"
}
]
},
{
"params": [
{
"name": "callback"
}
]
}
],
"desc": "This method is almost identical to domain.bind(callback)
. However, in\naddition to catching thrown errors, it will also intercept Error
\nobjects sent as the first argument to the function.
In this way, the common if (err) return callback(err);
pattern can be replaced\nwith a single error handler in a single place.
const d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n fs.readFile(filename, 'utf8', d.intercept((data) => {\n // note, the first argument is never passed to the\n // callback since it is assumed to be the 'Error' argument\n // and thus intercepted by the domain.\n\n // if this throws, it will also be passed to the domain\n // so the error-handling logic can be moved to the 'error'\n // event on the domain instead of being repeated throughout\n // the program.\n return cb(null, JSON.parse(data));\n }));\n}\n\nd.on('error', (er) => {\n // an error occurred somewhere.\n // if we throw it now, it will crash the program\n // with the normal line number and stack message.\n});\n
\n"
},
{
"textRaw": "domain.enter()",
"type": "method",
"name": "enter",
"desc": "The enter
method is plumbing used by the run
, bind
, and intercept
\nmethods to set the active domain. It sets domain.active
and process.domain
\nto the domain, and implicitly pushes the domain onto the domain stack managed\nby the domain module (see domain.exit()
for details on the domain stack). The\ncall to enter
delimits the beginning of a chain of asynchronous calls and I/O\noperations bound to a domain.
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.
If the domain on which enter
is called has been disposed, enter
will return\nwithout setting the domain.
The exit
method exits the current domain, popping it off the domain stack.\nAny time execution is going to switch to the context of a different chain of\nasynchronous calls, it's important to ensure that the current domain is exited.\nThe call to exit
delimits either the end of or an interruption to the chain\nof asynchronous calls and I/O operations bound to a domain.
If there are multiple, nested domains bound to the current execution context,\nexit
will exit any domains nested within this domain.
Calling exit
changes only the active domain, and does not alter the domain\nitself. enter
and exit
can be called an arbitrary number of times on a\nsingle domain.
If the domain on which exit
is called has been disposed, exit
will return\nwithout exiting the domain.
Stability: 0 - Deprecated. Please recover from failed IO actions\nexplicitly via error event handlers set on the domain.
\nOnce 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.
An array of timers and event emitters that have been explicitly added\nto the domain.
\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.
\nFor instance: a net.Server
object emits an event each time a peer\nconnects to it; a fs.ReadStream
emits an event when the file is opened;\na stream emits an event whenever data is available to be read.
All objects that emit events are instances of the EventEmitter
class. These\nobjects expose an eventEmitter.on()
function that allows one or more\nfunctions to be attached to named events emitted by the object. Typically,\nevent names are camel-cased strings but any valid JavaScript property key\ncan be used.
When the EventEmitter
object emits an event, all of the functions attached\nto that specific event are called synchronously. Any values returned by the\ncalled listeners are ignored and will be discarded.
The following example shows a simple EventEmitter
instance with a single\nlistener. The eventEmitter.on()
method is used to register listeners, while\nthe eventEmitter.emit()
method is used to trigger the event.
const EventEmitter = require('events');\n\nclass MyEmitter extends EventEmitter {}\n\nconst myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {\n console.log('an event occurred!');\n});\nmyEmitter.emit('event');\n
\n",
"modules": [
{
"textRaw": "Passing arguments and `this` to listeners",
"name": "passing_arguments_and_`this`_to_listeners",
"desc": "The eventEmitter.emit()
method allows an arbitrary set of arguments to be\npassed to the listener functions. It is important to keep in mind that when an\nordinary listener function is called by the EventEmitter
, the standard this
\nkeyword is intentionally set to reference the EventEmitter
to which the\nlistener is attached.
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
\nIt is possible to use ES6 Arrow Functions as listeners, however, when doing so,\nthe this
keyword will no longer reference the EventEmitter
instance:
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n console.log(a, b, this);\n // Prints: a b {}\n});\nmyEmitter.emit('event', 'a', 'b');\n
\n",
"type": "module",
"displayName": "Passing arguments and `this` to listeners"
},
{
"textRaw": "Asynchronous vs. Synchronous",
"name": "asynchronous_vs._synchronous",
"desc": "The 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:
const myEmitter = new MyEmitter();\nmyEmitter.on('event', (a, b) => {\n setImmediate(() => {\n console.log('this happens asynchronously');\n });\n});\nmyEmitter.emit('event', 'a', 'b');\n
\n",
"type": "module",
"displayName": "Asynchronous vs. Synchronous"
},
{
"textRaw": "Handling events only once",
"name": "handling_events_only_once",
"desc": "When a listener is registered using the eventEmitter.on()
method, that\nlistener will be invoked every time the named event is emitted.
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
\nUsing the eventEmitter.once()
method, it is possible to register a listener\nthat is called at most once for a particular event. Once the event is emitted,\nthe listener is unregistered and then called.
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
\n",
"type": "module",
"displayName": "Handling events only once"
},
{
"textRaw": "Error events",
"name": "error_events",
"desc": "When an error occurs within an EventEmitter
instance, the typical action is\nfor an 'error'
event to be emitted. These are treated as special cases\nwithin Node.js.
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.
const myEmitter = new MyEmitter();\nmyEmitter.emit('error', new Error('whoops!'));\n// Throws and crashes Node.js\n
\nTo guard against crashing the Node.js process, a listener can be registered\non the process
object's uncaughtException
event or the domain
module\ncan be used. (Note, however, that the domain
module has been deprecated)
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
\nAs a best practice, listeners should always be added for the 'error'
events.
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
\n",
"type": "module",
"displayName": "Error events"
}
],
"classes": [
{
"textRaw": "Class: EventEmitter",
"type": "class",
"name": "EventEmitter",
"meta": {
"added": [
"v0.1.26"
]
},
"desc": "The EventEmitter
class is defined and exposed by the events
module:
const EventEmitter = require('events');\n
\nAll EventEmitters emit the event 'newListener'
when new listeners are\nadded and 'removeListener'
when existing listeners are removed.
The EventEmitter
instance will emit its own 'newListener'
event before\na listener is added to its internal array of listeners.
Listeners registered for the 'newListener'
event will be passed the event\nname and a reference to the listener being added.
The fact that the event is triggered before adding the listener has a subtle\nbut important side effect: any additional listeners registered to the same\nname
within the 'newListener'
callback will be inserted before the\nlistener that is in the process of being added.
const myEmitter = new MyEmitter();\n// Only do this once so we don't loop forever\nmyEmitter.once('newListener', (event, listener) => {\n if (event === 'event') {\n // Insert a new listener in front\n myEmitter.on('event', () => {\n console.log('B');\n });\n }\n});\nmyEmitter.on('event', () => {\n console.log('A');\n});\nmyEmitter.emit('event');\n// Prints:\n// B\n// A\n
\n"
},
{
"textRaw": "Event: 'removeListener'",
"type": "event",
"name": "removeListener",
"meta": {
"added": [
"v0.9.3"
]
},
"params": [],
"desc": "The 'removeListener'
event is emitted after the listener
is removed.
A class method that returns the number of listeners for the given eventName
\nregistered on the given emitter
.
const myEmitter = new MyEmitter();\nmyEmitter.on('event', () => {});\nmyEmitter.on('event', () => {});\nconsole.log(EventEmitter.listenerCount(myEmitter, 'event'));\n// Prints: 2\n
\n",
"signatures": [
{
"params": [
{
"name": "emitter"
},
{
"name": "eventName"
}
]
}
]
},
{
"textRaw": "emitter.addListener(eventName, listener)",
"type": "method",
"name": "addListener",
"meta": {
"added": [
"v0.1.26"
]
},
"desc": "Alias for emitter.on(eventName, listener)
.
Synchronously calls each of the listeners registered for the event named\neventName
, in the order they were registered, passing the supplied arguments\nto each.
Returns true
if the event had listeners, false
otherwise.
Returns an array listing the events for which the emitter has registered\nlisteners. The values in the array will be strings or Symbols.
\nconst EventEmitter = require('events');\nconst myEE = new EventEmitter();\nmyEE.on('foo', () => {});\nmyEE.on('bar', () => {});\n\nconst sym = Symbol('symbol');\nmyEE.on(sym, () => {});\n\nconsole.log(myEE.eventNames());\n// Prints: [ 'foo', 'bar', Symbol(symbol) ]\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "emitter.getMaxListeners()",
"type": "method",
"name": "getMaxListeners",
"meta": {
"added": [
"v1.0.0"
]
},
"desc": "Returns the current max listener value for the EventEmitter
which is either\nset by emitter.setMaxListeners(n)
or defaults to\nEventEmitter.defaultMaxListeners
.
Returns the number of listeners listening to the event named eventName
.
Returns a copy of the array of listeners for the event named eventName
.
server.on('connection', (stream) => {\n console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection')));\n// Prints: [ [Function] ]\n
\n",
"signatures": [
{
"params": [
{
"name": "eventName"
}
]
}
]
},
{
"textRaw": "emitter.on(eventName, listener)",
"type": "method",
"name": "on",
"meta": {
"added": [
"v0.1.101"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`eventName` {String|Symbol} The name of the event. ",
"name": "eventName",
"type": "String|Symbol",
"desc": "The name of the event."
},
{
"textRaw": "`listener` {Function} The callback function ",
"name": "listener",
"type": "Function",
"desc": "The callback function"
}
]
},
{
"params": [
{
"name": "eventName"
},
{
"name": "listener"
}
]
}
],
"desc": "Adds the listener
function to the end of the listeners array for the\nevent named eventName
. No checks are made to see if the listener
has\nalready been added. Multiple calls passing the same combination of eventName
\nand listener
will result in the listener
being added, and called, multiple\ntimes.
server.on('connection', (stream) => {\n console.log('someone connected!');\n});\n
\nReturns a reference to the EventEmitter
, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The\nemitter.prependListener()
method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.
const myEE = new EventEmitter();\nmyEE.on('foo', () => console.log('a'));\nmyEE.prependListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n// b\n// a\n
\n"
},
{
"textRaw": "emitter.once(eventName, listener)",
"type": "method",
"name": "once",
"meta": {
"added": [
"v0.3.0"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`eventName` {String|Symbol} The name of the event. ",
"name": "eventName",
"type": "String|Symbol",
"desc": "The name of the event."
},
{
"textRaw": "`listener` {Function} The callback function ",
"name": "listener",
"type": "Function",
"desc": "The callback function"
}
]
},
{
"params": [
{
"name": "eventName"
},
{
"name": "listener"
}
]
}
],
"desc": "Adds a one time listener
function for the event named eventName
. The\nnext time eventName
is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {\n console.log('Ah, we have our first user!');\n});\n
\nReturns a reference to the EventEmitter
, so that calls can be chained.
By default, event listeners are invoked in the order they are added. The\nemitter.prependOnceListener()
method can be used as an alternative to add the\nevent listener to the beginning of the listeners array.
const myEE = new EventEmitter();\nmyEE.once('foo', () => console.log('a'));\nmyEE.prependOnceListener('foo', () => console.log('b'));\nmyEE.emit('foo');\n// Prints:\n// b\n// a\n
\n"
},
{
"textRaw": "emitter.prependListener(eventName, listener)",
"type": "method",
"name": "prependListener",
"meta": {
"added": [
"v6.0.0"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`eventName` {String|Symbol} The name of the event. ",
"name": "eventName",
"type": "String|Symbol",
"desc": "The name of the event."
},
{
"textRaw": "`listener` {Function} The callback function ",
"name": "listener",
"type": "Function",
"desc": "The callback function"
}
]
},
{
"params": [
{
"name": "eventName"
},
{
"name": "listener"
}
]
}
],
"desc": "Adds the listener
function to the beginning of the listeners array for the\nevent named eventName
. No checks are made to see if the listener
has\nalready been added. Multiple calls passing the same combination of eventName
\nand listener
will result in the listener
being added, and called, multiple\ntimes.
server.prependListener('connection', (stream) => {\n console.log('someone connected!');\n});\n
\nReturns a reference to the EventEmitter
, so that calls can be chained.
Adds a one time listener
function for the event named eventName
to the\nbeginning of the listeners array. The next time eventName
is triggered, this\nlistener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {\n console.log('Ah, we have our first user!');\n});\n
\nReturns a reference to the EventEmitter
, so that calls can be chained.
Removes all listeners, or those of the specified eventName
.
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).
Returns a reference to the EventEmitter
, so that calls can be chained.
Removes the specified listener
from the listener array for the event named\neventName
.
var callback = (stream) => {\n console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);\n
\nremoveListener
will remove, at most, one instance of a listener from the\nlistener array. If any single listener has been added multiple times to the\nlistener array for the specified eventName
, then removeListener
must be\ncalled multiple times to remove each instance.
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.
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
\nBecause listeners are managed using an internal array, calling this will\nchange the position indices of any listener registered after the listener\nbeing removed. This will not impact the order in which listeners are called,\nbut it means that any copies of the listener array as returned by\nthe emitter.listeners()
method will need to be recreated.
Returns a reference to the EventEmitter
, so that calls can be chained.
By default EventEmitters will print a warning if more than 10
listeners are\nadded for a particular event. This is a useful default that helps finding\nmemory leaks. Obviously, not all events should be limited to just 10 listeners.\nThe emitter.setMaxListeners()
method allows the limit to be modified for this\nspecific EventEmitter
instance. The value can be set to Infinity
(or 0
)\nto indicate an unlimited number of listeners.
Returns a reference to the EventEmitter
, so that calls can be chained.
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.
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
.
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:
emitter.setMaxListeners(emitter.getMaxListeners() + 1);\nemitter.once('event', () => {\n // do stuff\n emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));\n});\n
\nThe --trace-warnings
command line flag can be used to display the\nstack trace for such warnings.
The emitted warning can be inspected with process.on('warning')
and will\nhave the additional emitter
, type
and count
properties, referring to\nthe event emitter instance, the event’s name and the number of attached\nlisteners, respectively.\nIts name
property is set to 'MaxListenersExceededWarning'
.
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.
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
.
When using the synchronous form any exceptions are immediately thrown.\nYou can use try/catch to handle exceptions or allow them to bubble up.
\nHere is an example of the asynchronous version:
\nconst fs = require('fs');\n\nfs.unlink('/tmp/hello', (err) => {\n if (err) throw err;\n console.log('successfully deleted /tmp/hello');\n});\n
\nHere is the synchronous version:
\nconst fs = require('fs');\n\nfs.unlinkSync('/tmp/hello');\nconsole.log('successfully deleted /tmp/hello');\n
\nWith the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:
\nfs.rename('/tmp/hello', '/tmp/world', (err) => {\n if (err) throw err;\n console.log('renamed complete');\n});\nfs.stat('/tmp/world', (err, stats) => {\n if (err) throw err;\n console.log(`stats: ${JSON.stringify(stats)}`);\n});\n
\nIt could be that fs.stat
is executed before fs.rename
.\nThe correct way to do this is to chain the callbacks.
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
\nIn 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.
\nThe relative path to a filename can be used. Remember, however, that this path\nwill be relative to process.cwd()
.
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:
$ cat script.js\nfunction bad() {\n require('fs').readFile('/');\n}\nbad();\n\n$ env NODE_DEBUG=fs node script.js\nfs.js:88\n throw backtrace;\n ^\nError: EISDIR: illegal operation on a directory, read\n <stack trace.>\n
\n",
"modules": [
{
"textRaw": "Buffer API",
"name": "buffer_api",
"meta": {
"added": [
"v6.0.0"
]
},
"desc": "fs
functions support passing and receiving paths as both strings\nand Buffers. The latter is intended to make it possible to work with\nfilesystems that allow for non-UTF-8 filenames. For most typical\nuses, working with paths as Buffers will be unnecessary, as the string\nAPI converts to and from UTF-8 automatically.
Note that on certain file systems (such as NTFS and HFS+) filenames\nwill always be encoded as UTF-8. On such file systems, passing\nnon-UTF-8 encoded Buffers to fs
functions will not work as expected.
The following constants are exported by fs.constants
. Note: Not every\nconstant will be available on every operating system.
The following constants are meant for use with fs.access()
.
Constant | \nDescription | \n
---|---|
F_OK | \n Flag indicating that the file is visible to the calling process. | \n
R_OK | \n Flag indicating that the file can be read by the calling process. | \n
W_OK | \n Flag indicating that the file can be written by the calling\n process. | \n
X_OK | \n Flag indicating that the file can be executed by the calling\n process. | \n
The following constants are meant for use with fs.open()
.
Constant | \nDescription | \n
---|---|
O_RDONLY | \n Flag indicating to open a file for read-only access. | \n
O_WRONLY | \n Flag indicating to open a file for write-only access. | \n
O_RDWR | \n Flag indicating to open a file for read-write access. | \n
O_CREAT | \n Flag indicating to create the file if it does not already exist. | \n
O_EXCL | \n Flag indicating that opening a file should fail if the\n O_CREAT flag is set and the file already exists. | \n
O_NOCTTY | \n Flag indicating that if path identifies a terminal device, opening the\n path shall not cause that terminal to become the controlling terminal for\n the process (if the process does not already have one). | \n
O_TRUNC | \n Flag indicating that if the file exists and is a regular file, and the\n file is opened successfully for write access, its length shall be truncated\n to zero. | \n
O_APPEND | \n Flag indicating that data will be appended to the end of the file. | \n
O_DIRECTORY | \n Flag indicating that the open should fail if the path is not a\n directory. | \n
O_NOATIME | \n Flag indicating reading accesses to the file system will no longer\n result in an update to the atime information associated with the file.\n This flag is available on Linux operating systems only. | \n
O_NOFOLLOW | \n Flag indicating that the open should fail if the path is a symbolic\n link. | \n
O_SYNC | \n Flag indicating that the file is opened for synchronous I/O. | \n
O_SYMLINK | \n Flag indicating to open the symbolic link itself rather than the\n resource it is pointing to. | \n
O_DIRECT | \n When set, an attempt will be made to minimize caching effects of file\n I/O. | \n
O_NONBLOCK | \n Flag indicating to open the file in nonblocking mode when possible. | \n
The following constants are meant for use with the fs.Stats
object's\nmode
property for determining a file's type.
Constant | \nDescription | \n
---|---|
S_IFMT | \n Bit mask used to extract the file type code. | \n
S_IFREG | \n File type constant for a regular file. | \n
S_IFDIR | \n File type constant for a directory. | \n
S_IFCHR | \n File type constant for a character-oriented device file. | \n
S_IFBLK | \n File type constant for a block-oriented device file. | \n
S_IFIFO | \n File type constant for a FIFO/pipe. | \n
S_IFLNK | \n File type constant for a symbolic link. | \n
S_IFSOCK | \n File type constant for a socket. | \n
The following constants are meant for use with the fs.Stats
object's\nmode
property for determining the access permissions for a file.
Constant | \nDescription | \n
---|---|
S_IRWXU | \n File mode indicating readable, writable and executable by owner. | \n
S_IRUSR | \n File mode indicating readable by owner. | \n
S_IWUSR | \n File mode indicating writable by owner. | \n
S_IXUSR | \n File mode indicating executable by owner. | \n
S_IRWXG | \n File mode indicating readable, writable and executable by group. | \n
S_IRGRP | \n File mode indicating readable by group. | \n
S_IWGRP | \n File mode indicating writable by group. | \n
S_IXGRP | \n File mode indicating executable by group. | \n
S_IRWXO | \n File mode indicating readable, writable and executable by others. | \n
S_IROTH | \n File mode indicating readable by others. | \n
S_IWOTH | \n File mode indicating writable by others. | \n
S_IXOTH | \n File mode indicating executable by others. | \n
Objects returned from fs.watch()
are of this type.
The listener
callback provided to fs.watch()
receives the returned FSWatcher's\nchange
events.
The object itself emits these events:
\n", "events": [ { "textRaw": "Event: 'change'", "type": "event", "name": "change", "meta": { "added": [ "v0.5.8" ] }, "params": [], "desc": "Emitted when something changes in a watched directory or file.\nSee more details in fs.watch()
.
The filename
argument may not be provided depending on operating system\nsupport. If filename
is provided, it will be provided as a Buffer
if\nfs.watch()
is called with its encoding
option set to 'buffer'
, otherwise\nfilename
will be a string.
// Example when handled through fs.watch listener\nfs.watch('./tmp', {encoding: 'buffer'}, (eventType, filename) => {\n if (filename)\n console.log(filename);\n // Prints: <Buffer ...>\n});\n
\n"
},
{
"textRaw": "Event: 'error'",
"type": "event",
"name": "error",
"meta": {
"added": [
"v0.5.8"
]
},
"params": [],
"desc": "Emitted when an error occurs.
\n" } ], "methods": [ { "textRaw": "watcher.close()", "type": "method", "name": "close", "meta": { "added": [ "v0.5.8" ] }, "desc": "Stop watching for changes on the given fs.FSWatcher
.
ReadStream
is a Readable Stream.
Emitted when the ReadStream's file is opened.
\n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.93" ] }, "desc": "Emitted when the ReadStream
's underlying file descriptor has been closed\nusing the fs.close()
method.
The number of bytes read so far.
\n" }, { "textRaw": "readStream.path", "name": "path", "meta": { "added": [ "v0.1.93" ] }, "desc": "The path to the file the stream is reading from as specified in the first\nargument to fs.createReadStream()
. If path
is passed as a string, then\nreadStream.path
will be a string. If path
is passed as a Buffer
, then\nreadStream.path
will be a Buffer
.
Objects returned from fs.stat()
, fs.lstat()
and fs.fstat()
and their\nsynchronous counterparts are of this type.
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(only valid with fs.lstat()
)stats.isFIFO()
stats.isSocket()
For a regular file util.inspect(stats)
would return a string very\nsimilar to this:
{\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
\nPlease note that atime
, mtime
, birthtime
, and ctime
are\ninstances of Date
object and to compare the values of\nthese objects you should use appropriate methods. For most general\nuses getTime()
will return the number of\nmilliseconds elapsed since 1 January 1970 00:00:00 UTC and this\ninteger should be sufficient for any comparison, however there are\nadditional methods which can be used for displaying fuzzy information.\nMore details can be found in the MDN JavaScript Reference\npage.
The times in the stat object have the following semantics:
\natime
"Access Time" - Time when file data last accessed. Changed\nby the mknod(2), utimes(2), and read(2) system calls.mtime
"Modified Time" - Time when file data last modified.\nChanged by the mknod(2), utimes(2), and write(2) system calls.ctime
"Change Time" - Time when file status was last changed\n(inode data modification). Changed by the chmod(2), chown(2),\nlink(2), mknod(2), rename(2), unlink(2), utimes(2),\nread(2), and write(2) system calls.birthtime
"Birth Time" - Time of file creation. Set once when the\nfile is created. On filesystems where birthtime is not available,\nthis field may instead hold either the ctime
or\n1970-01-01T00:00Z
(ie, unix epoch timestamp 0
). Note that this\nvalue may be greater than atime
or mtime
in this case. On Darwin\nand other FreeBSD variants, also set if the atime
is explicitly\nset to an earlier value than the current birthtime
using the\nutimes(2) system call.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.
WriteStream
is a Writable Stream.
Emitted when the WriteStream's file is opened.
\n" }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.1.93" ] }, "desc": "Emitted when the WriteStream
's underlying file descriptor has been closed\nusing the fs.close()
method.
The number of bytes written so far. Does not include data that is still queued\nfor writing.
\n" }, { "textRaw": "writeStream.path", "name": "path", "meta": { "added": [ "v0.1.93" ] }, "desc": "The path to the file the stream is writing to as specified in the first\nargument to fs.createWriteStream()
. If path
is passed as a string, then\nwriteStream.path
will be a string. If path
is passed as a Buffer
, then\nwriteStream.path
will be a Buffer
.
Tests a user's permissions for the file or directory specified by path
.\nThe mode
argument is an optional integer that specifies the accessibility\nchecks to be performed. The following constants define the possible values of\nmode
. It is possible to create a mask consisting of the bitwise OR of two or\nmore values.
fs.constants.F_OK
- path
is visible to the calling process. This is useful\nfor determining if a file exists, but says nothing about rwx
permissions.\nDefault if no mode
is specified.fs.constants.R_OK
- path
can be read by the calling process.fs.constants.W_OK
- path
can be written by the calling process.fs.constants.X_OK
- path
can be executed by the calling process. This has\nno effect on Windows (will behave like fs.constants.F_OK
).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.
fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {\n console.log(err ? 'no access!' : 'can read/write');\n});\n
\nUsing fs.access()
to check for the accessibility of a file before calling\nfs.open()
, fs.readFile()
or fs.writeFile()
is not recommended. Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file is not accessible.
For example:
\nwrite (NOT RECOMMENDED)
\nfs.access('myfile', (err) => {\n if (!err) {\n console.error('myfile already exists');\n return;\n }\n\n fs.open('myfile', 'wx', (err, fd) => {\n if (err) throw err;\n writeMyData(fd);\n });\n});\n
\nwrite (RECOMMENDED)
\nfs.open('myfile', 'wx', (err, fd) => {\n if (err) {\n if (err.code === "EEXIST") {\n console.error('myfile already exists');\n return;\n } else {\n throw err;\n }\n }\n\n writeMyData(fd);\n});\n
\nread (NOT RECOMMENDED)
\nfs.access('myfile', (err) => {\n if (err) {\n if (err.code === "ENOENT") {\n console.error('myfile does not exist');\n return;\n } else {\n throw err;\n }\n }\n\n fs.open('myfile', 'r', (err, fd) => {\n if (err) throw err;\n readMyData(fd);\n });\n});\n
\nread (RECOMMENDED)
\nfs.open('myfile', 'r', (err, fd) => {\n if (err) {\n if (err.code === "ENOENT") {\n console.error('myfile does not exist');\n return;\n } else {\n throw err;\n }\n }\n\n readMyData(fd);\n});\n
\nThe "not recommended" examples above check for accessibility and then use the\nfile; the "recommended" examples are better because they use the file directly\nand handle the error, if any.
\nIn general, check for the accessibility of a file only if the file won’t be\nused directly, for example when its accessibility is a signal from another\nprocess.
\n" }, { "textRaw": "fs.accessSync(path[, mode])", "type": "method", "name": "accessSync", "meta": { "added": [ "v0.11.15" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" }, { "textRaw": "`mode` {Integer} ", "name": "mode", "type": "Integer", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "mode", "optional": true } ] } ], "desc": "Synchronous version of fs.access()
. This throws if any accessibility\nchecks fail, and does nothing otherwise.
Asynchronously append data to a file, creating the file if it does not yet exist.\ndata
can be a string or a buffer.
Example:
\nfs.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
\nIf options
is a string, then it specifies the encoding. Example:
fs.appendFile('message.txt', 'data to append', 'utf8', callback);\n
\nAny specified file descriptor has to have been opened for appending.
\nNote: If a file descriptor is specified as the file
, it will not be closed\nautomatically.
The synchronous version of fs.appendFile()
. Returns undefined
.
Asynchronous chmod(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.chmodSync(path, mode)", "type": "method", "name": "chmodSync", "meta": { "added": [ "v0.6.7" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" }, { "textRaw": "`mode` {Integer} ", "name": "mode", "type": "Integer" } ] }, { "params": [ { "name": "path" }, { "name": "mode" } ] } ], "desc": "Synchronous chmod(2). Returns undefined
.
Asynchronous chown(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.chownSync(path, uid, gid)", "type": "method", "name": "chownSync", "meta": { "added": [ "v0.1.97" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" }, { "textRaw": "`uid` {Integer} ", "name": "uid", "type": "Integer" }, { "textRaw": "`gid` {Integer} ", "name": "gid", "type": "Integer" } ] }, { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ], "desc": "Synchronous chown(2). Returns undefined
.
Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.closeSync(fd)", "type": "method", "name": "closeSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {Integer} ", "name": "fd", "type": "Integer" } ] }, { "params": [ { "name": "fd" } ] } ], "desc": "Synchronous close(2). Returns undefined
.
Returns a new ReadStream
object. (See Readable Stream).
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.
options
is an object or string with the following defaults:
{\n flags: 'r',\n encoding: null,\n fd: null,\n mode: 0o666,\n autoClose: true\n}\n
\noptions
can include start
and end
values to read a range of bytes from\nthe file instead of the entire file. Both start
and end
are inclusive and\nstart counting at 0. If fd
is specified and start
is omitted or undefined
,\nfs.createReadStream()
reads sequentially from the current file position.\nThe encoding
can be any one of those accepted by Buffer
.
If fd
is specified, ReadStream
will ignore the path
argument and will use\nthe specified file descriptor. This means that no 'open'
event will be\nemitted. Note that fd
should be blocking; non-blocking fd
s should be passed\nto net.Socket
.
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.
mode
sets the file mode (permission and sticky bits), but only if the\nfile was created.
An example to read the last 10 bytes of a file which is 100 bytes long:
\nfs.createReadStream('sample.txt', {start: 90, end: 99});\n
\nIf options
is a string, then it specifies the encoding.
Returns a new WriteStream
object. (See Writable Stream).
options
is an object or string with the following defaults:
{\n flags: 'w',\n defaultEncoding: 'utf8',\n fd: null,\n mode: 0o666,\n autoClose: true\n}\n
\noptions
may also include a start
option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags
mode of r+
rather than the\ndefault mode w
. The defaultEncoding
can be any one of those accepted by\nBuffer
.
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.
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\nfd
s should be passed to net.Socket
.
If options
is a string, then it specifies the encoding.
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:
fs.exists('/etc/passwd', (exists) => {\n console.log(exists ? 'it\\'s there' : 'no passwd!');\n});\n
\nNote that the parameter to this callback is not consistent with other\nNode.js callbacks. Normally, the first parameter to a Node.js callback is\nan err
parameter, optionally followed by other parameters. The\nfs.exists()
callback has only one boolean parameter. This is one reason\nfs.access()
is recommended instead of fs.exists()
.
Using fs.exists()
to check for the existence of a file before calling\nfs.open()
, fs.readFile()
or fs.writeFile()
is not recommended. Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file does not exist.
For example:
\nwrite (NOT RECOMMENDED)
\nfs.exists('myfile', (exists) => {\n if (exists) {\n console.error('myfile already exists');\n } else {\n fs.open('myfile', 'wx', (err, fd) => {\n if (err) throw err;\n writeMyData(fd);\n });\n }\n});\n
\nwrite (RECOMMENDED)
\nfs.open('myfile', 'wx', (err, fd) => {\n if (err) {\n if (err.code === "EEXIST") {\n console.error('myfile already exists');\n return;\n } else {\n throw err;\n }\n }\n writeMyData(fd);\n});\n
\nread (NOT RECOMMENDED)
\nfs.exists('myfile', (exists) => {\n if (exists) {\n fs.open('myfile', 'r', (err, fd) => {\n readMyData(fd);\n });\n } else {\n console.error('myfile does not exist');\n }\n});\n
\nread (RECOMMENDED)
\nfs.open('myfile', 'r', (err, fd) => {\n if (err) {\n if (err.code === "ENOENT") {\n console.error('myfile does not exist');\n return;\n } else {\n throw err;\n }\n } else {\n readMyData(fd);\n }\n});\n
\nThe "not recommended" examples above check for existence and then use the\nfile; the "recommended" examples are better because they use the file directly\nand handle the error, if any.
\nIn general, check for the existence of a file only if the file won’t be\nused directly, for example when its existence is a signal from another\nprocess.
\n" }, { "textRaw": "fs.existsSync(path)", "type": "method", "name": "existsSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" } ] }, { "params": [ { "name": "path" } ] } ], "desc": "Synchronous version of fs.exists()
.\nReturns true
if the file exists, false
otherwise.
Note that fs.exists()
is deprecated, but fs.existsSync()
is not.\n(The callback
parameter to fs.exists()
accepts parameters that are\ninconsistent with other Node.js callbacks. fs.existsSync()
does not use\na callback.)
Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.
\n" }, { "textRaw": "fs.fchmodSync(fd, mode)", "type": "method", "name": "fchmodSync", "meta": { "added": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {Integer} ", "name": "fd", "type": "Integer" }, { "textRaw": "`mode` {Integer} ", "name": "mode", "type": "Integer" } ] }, { "params": [ { "name": "fd" }, { "name": "mode" } ] } ], "desc": "Synchronous fchmod(2). Returns undefined
.
Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.fchownSync(fd, uid, gid)", "type": "method", "name": "fchownSync", "meta": { "added": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {Integer} ", "name": "fd", "type": "Integer" }, { "textRaw": "`uid` {Integer} ", "name": "uid", "type": "Integer" }, { "textRaw": "`gid` {Integer} ", "name": "gid", "type": "Integer" } ] }, { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" } ] } ], "desc": "Synchronous fchown(2). Returns undefined
.
Asynchronous fdatasync(2). No arguments other than a possible exception are\ngiven to the completion callback.
\n" }, { "textRaw": "fs.fdatasyncSync(fd)", "type": "method", "name": "fdatasyncSync", "meta": { "added": [ "v0.1.96" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {Integer} ", "name": "fd", "type": "Integer" } ] }, { "params": [ { "name": "fd" } ] } ], "desc": "Synchronous fdatasync(2). Returns undefined
.
Asynchronous fstat(2). The callback gets two arguments (err, stats)
where\nstats
is an fs.Stats
object. fstat()
is identical to stat()
,\nexcept that the file to be stat-ed is specified by the file descriptor fd
.
Synchronous fstat(2). Returns an instance of fs.Stats
.
Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.fsyncSync(fd)", "type": "method", "name": "fsyncSync", "meta": { "added": [ "v0.1.96" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {Integer} ", "name": "fd", "type": "Integer" } ] }, { "params": [ { "name": "fd" } ] } ], "desc": "Synchronous fsync(2). Returns undefined
.
Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.
\nIf the file referred to by the file descriptor was larger than len
bytes, only\nthe first len
bytes will be retained in the file.
For example, the following program retains only the first four bytes of the file
\nconsole.log(fs.readFileSync('temp.txt', 'utf8'));\n// Prints: Node.js\n\n// get the file descriptor of the file to be truncated\nconst fd = fs.openSync('temp.txt', 'r+');\n\n// truncate the file to first four bytes\nfs.ftruncate(fd, 4, (err) => {\n assert.ifError(err);\n console.log(fs.readFileSync('temp.txt', 'utf8'));\n});\n// Prints: Node\n
\nIf the file previously was shorter than len
bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'). For example,
console.log(fs.readFileSync('temp.txt', 'utf-8'));\n// Prints: Node.js\n\n// get the file descriptor of the file to be truncated\nconst fd = fs.openSync('temp.txt', 'r+');\n\n// truncate the file to 10 bytes, whereas the actual size is 7 bytes\nfs.ftruncate(fd, 10, (err) => {\n assert.ifError(!err);\n console.log(fs.readFileSync('temp.txt'));\n});\n// Prints: <Buffer 4e 6f 64 65 2e 6a 73 00 00 00>\n// ('Node.js\\0\\0\\0' in UTF8)\n
\nThe last three bytes are null bytes ('\\0'), to compensate the over-truncation.
\n" }, { "textRaw": "fs.ftruncateSync(fd, len)", "type": "method", "name": "ftruncateSync", "meta": { "added": [ "v0.8.6" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {Integer} ", "name": "fd", "type": "Integer" }, { "textRaw": "`len` {Integer} default = `0` ", "name": "len", "type": "Integer", "desc": "default = `0`" } ] }, { "params": [ { "name": "fd" }, { "name": "len" } ] } ], "desc": "Synchronous ftruncate(2). Returns undefined
.
Change the file timestamps of a file referenced by the supplied file\ndescriptor.
\n" }, { "textRaw": "fs.futimesSync(fd, atime, mtime)", "type": "method", "name": "futimesSync", "meta": { "added": [ "v0.4.2" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {Integer} ", "name": "fd", "type": "Integer" }, { "textRaw": "`atime` {Integer} ", "name": "atime", "type": "Integer" }, { "textRaw": "`mtime` {Integer} ", "name": "mtime", "type": "Integer" } ] }, { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] } ], "desc": "Synchronous version of fs.futimes()
. Returns undefined
.
Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.
\nOnly available on Mac OS X.
\n" }, { "textRaw": "fs.lchmodSync(path, mode)", "type": "method", "name": "lchmodSync", "meta": { "deprecated": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" }, { "textRaw": "`mode` {Integer} ", "name": "mode", "type": "Integer" } ] }, { "params": [ { "name": "path" }, { "name": "mode" } ] } ], "desc": "Synchronous lchmod(2). Returns undefined
.
Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.lchownSync(path, uid, gid)", "type": "method", "name": "lchownSync", "meta": { "deprecated": [ "v0.4.7" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" }, { "textRaw": "`uid` {Integer} ", "name": "uid", "type": "Integer" }, { "textRaw": "`gid` {Integer} ", "name": "gid", "type": "Integer" } ] }, { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ], "desc": "Synchronous lchown(2). Returns undefined
.
Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.
\n" }, { "textRaw": "fs.linkSync(existingPath, newPath)", "type": "method", "name": "linkSync", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`existingPath` {String | Buffer} ", "name": "existingPath", "type": "String | Buffer" }, { "textRaw": "`newPath` {String | Buffer} ", "name": "newPath", "type": "String | Buffer" } ] }, { "params": [ { "name": "existingPath" }, { "name": "newPath" } ] } ], "desc": "Synchronous link(2). Returns undefined
.
Asynchronous lstat(2). The callback gets two arguments (err, stats)
where\nstats
is a fs.Stats
object. lstat()
is identical to stat()
,\nexcept that if path
is a symbolic link, then the link itself is stat-ed,\nnot the file that it refers to.
Synchronous lstat(2). Returns an instance of fs.Stats
.
Asynchronous mkdir(2). No arguments other than a possible exception are given\nto the completion callback. mode
defaults to 0o777
.
Synchronous mkdir(2). Returns undefined
.
Creates a unique temporary directory.
\nGenerates six random characters to be appended behind a required\nprefix
to create a unique temporary directory.
The created folder path is passed as a string to the callback's second\nparameter.
\nThe optional options
argument can be a string specifying an encoding, or an\nobject with an encoding
property specifying the character encoding to use.
Example:
\nfs.mkdtemp('/tmp/foo-', (err, folder) => {\n if (err) throw err;\n console.log(folder);\n // Prints: /tmp/foo-itXde2\n});\n
\nNote: The fs.mkdtemp()
method will append the six randomly selected\ncharacters directly to the prefix
string. For instance, given a directory\n/tmp
, if the intention is to create a temporary directory within /tmp
,\nthe prefix
must end with a trailing platform-specific path separator\n(require('path').sep
).
// The parent directory for the new temporary directory\nconst tmpDir = '/tmp';\n\n// This method is *INCORRECT*:\nfs.mkdtemp(tmpDir, (err, folder) => {\n if (err) throw err;\n console.log(folder);\n // Will print something similar to `/tmpabc123`.\n // Note that a new temporary directory is created\n // at the file system root rather than *within*\n // the /tmp directory.\n});\n\n// This method is *CORRECT*:\nconst path = require('path');\nfs.mkdtemp(tmpDir + path.sep, (err, folder) => {\n if (err) throw err;\n console.log(folder);\n // Will print something similar to `/tmp/abc123`.\n // A new temporary directory is created within\n // the /tmp directory.\n});\n
\n"
},
{
"textRaw": "fs.mkdtempSync(prefix[, options])",
"type": "method",
"name": "mkdtempSync",
"meta": {
"added": [
"v5.10.0"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`prefix` {String} ",
"name": "prefix",
"type": "String"
},
{
"textRaw": "`options` {String | Object} ",
"options": [
{
"textRaw": "`encoding` {String} default = `'utf8'` ",
"name": "encoding",
"type": "String",
"desc": "default = `'utf8'`"
}
],
"name": "options",
"type": "String | Object",
"optional": true
}
]
},
{
"params": [
{
"name": "prefix"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "The synchronous version of fs.mkdtemp()
. Returns the created\nfolder path.
The optional options
argument can be a string specifying an encoding, or an\nobject with an encoding
property specifying the character encoding to use.
Asynchronous file open. See open(2). flags
can be:
'r'
- Open file for reading.\nAn exception occurs if the file does not exist.
'r+'
- Open file for reading and writing.\nAn exception occurs if the file does not exist.
'rs+'
- Open file for reading and writing in synchronous mode. Instructs\nthe operating system to bypass the local file system cache.
This is primarily useful for opening files on NFS mounts as it allows you to\nskip the potentially stale local cache. It has a very real impact on I/O\nperformance so don't use this flag unless you need it.
\nNote that this doesn't turn fs.open()
into a synchronous blocking call.\nIf that's what you want then you should be using fs.openSync()
'w'
- Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'wx'
- Like 'w'
but fails if path
exists.
'w+'
- Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'wx+'
- Like 'w+'
but fails if path
exists.
'a'
- Open file for appending.\nThe file is created if it does not exist.
'ax'
- Like 'a'
but fails if path
exists.
'a+'
- Open file for reading and appending.\nThe file is created if it does not exist.
'ax+'
- Like 'a+'
but fails if path
exists.
mode
sets the file mode (permission and sticky bits), but only if the file was\ncreated. It defaults to 0666
, readable and writable.
The callback gets two arguments (err, fd)
.
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.
flags
can also be a number as documented by open(2); commonly used constants\nare available from fs.constants
. On Windows, flags are translated to\ntheir equivalent ones where applicable, e.g. O_WRONLY
to FILE_GENERIC_WRITE
,\nor O_EXCL|O_CREAT
to CREATE_NEW
, as accepted by CreateFileW.
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.
\nNote: The behavior of fs.open()
is platform specific for some flags. As such,\nopening a directory on OS X and Linux with the 'a+'
flag - see example below -\nwill return an error. In contrast, on Windows and FreeBSD, a file descriptor\nwill be returned.
// OS X and Linux\nfs.open('<directory>', 'a+', (err, fd) => {\n // => [Error: EISDIR: illegal operation on a directory, open <directory>]\n});\n\n// Windows and FreeBSD\nfs.open('<directory>', 'a+', (err, fd) => {\n // => null, <fd>\n});\n
\n"
},
{
"textRaw": "fs.openSync(path, flags[, mode])",
"type": "method",
"name": "openSync",
"meta": {
"added": [
"v0.1.21"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`path` {String | Buffer} ",
"name": "path",
"type": "String | Buffer"
},
{
"textRaw": "`flags` {String | Number} ",
"name": "flags",
"type": "String | Number"
},
{
"textRaw": "`mode` {Integer} ",
"name": "mode",
"type": "Integer",
"optional": true
}
]
},
{
"params": [
{
"name": "path"
},
{
"name": "flags"
},
{
"name": "mode",
"optional": true
}
]
}
],
"desc": "Synchronous version of fs.open()
. Returns an integer representing the file\ndescriptor.
Read data from the file specified by fd
.
buffer
is the buffer that the data will be written to.
offset
is the offset in the buffer to start writing at.
length
is an integer specifying the number of bytes to read.
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.
The callback is given the three arguments, (err, bytesRead, buffer)
.
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 '..'
.
The optional options
argument can be a string specifying an encoding, or an\nobject with an encoding
property specifying the character encoding to use for\nthe filenames passed to the callback. If the encoding
is set to 'buffer'
,\nthe filenames returned will be passed as Buffer
objects.
Synchronous readdir(3). Returns an array of filenames excluding '.'
and\n'..'
.
The optional options
argument can be a string specifying an encoding, or an\nobject with an encoding
property specifying the character encoding to use for\nthe filenames passed to the callback. If the encoding
is set to 'buffer'
,\nthe filenames returned will be passed as Buffer
objects.
Asynchronously reads the entire contents of a file. Example:
\nfs.readFile('/etc/passwd', (err, data) => {\n if (err) throw err;\n console.log(data);\n});\n
\nThe callback is passed two arguments (err, data)
, where data
is the\ncontents of the file.
If no encoding is specified, then the raw buffer is returned.
\nIf options
is a string, then it specifies the encoding. Example:
fs.readFile('/etc/passwd', 'utf8', callback);\n
\nAny specified file descriptor has to support reading.
\nNote: If a file descriptor is specified as the file
, it will not be closed\nautomatically.
Synchronous version of fs.readFile
. Returns the contents of the file
.
If the encoding
option is specified then this function returns a\nstring. Otherwise it returns a buffer.
Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString)
.
The optional options
argument can be a string specifying an encoding, or an\nobject with an encoding
property specifying the character encoding to use for\nthe link path passed to the callback. If the encoding
is set to 'buffer'
,\nthe link path returned will be passed as a Buffer
object.
Synchronous readlink(2). Returns the symbolic link's string value.
\nThe optional options
argument can be a string specifying an encoding, or an\nobject with an encoding
property specifying the character encoding to use for\nthe link path passed to the callback. If the encoding
is set to 'buffer'
,\nthe link path returned will be passed as a Buffer
object.
Synchronous version of fs.read()
. Returns the number of bytesRead
.
Asynchronous realpath(3). The callback
gets two arguments (err,\nresolvedPath)
. May use process.cwd
to resolve relative paths.
Only paths that can be converted to UTF8 strings are supported.
\nThe optional options
argument can be a string specifying an encoding, or an\nobject with an encoding
property specifying the character encoding to use for\nthe path passed to the callback. If the encoding
is set to 'buffer'
,\nthe path returned will be passed as a Buffer
object.
Synchronous realpath(3). Returns the resolved path.
\nOnly paths that can be converted to UTF8 strings are supported.
\nThe optional options
argument can be a string specifying an encoding, or an\nobject with an encoding
property specifying the character encoding to use for\nthe returned value. If the encoding
is set to 'buffer'
, the path returned\nwill be passed as a Buffer
object.
Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.renameSync(oldPath, newPath)", "type": "method", "name": "renameSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`oldPath` {String | Buffer} ", "name": "oldPath", "type": "String | Buffer" }, { "textRaw": "`newPath` {String | Buffer} ", "name": "newPath", "type": "String | Buffer" } ] }, { "params": [ { "name": "oldPath" }, { "name": "newPath" } ] } ], "desc": "Synchronous rename(2). Returns undefined
.
Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.rmdirSync(path)", "type": "method", "name": "rmdirSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" } ] }, { "params": [ { "name": "path" } ] } ], "desc": "Synchronous rmdir(2). Returns undefined
.
Asynchronous stat(2). The callback gets two arguments (err, stats)
where\nstats
is an fs.Stats
object.
In case of an error, the err.code
will be one of Common System Errors.
Using fs.stat()
to check for the existence of a file before calling\nfs.open()
, fs.readFile()
or fs.writeFile()
is not recommended.\nInstead, user code should open/read/write the file directly and handle the\nerror raised if the file is not available.
To check if a file exists without manipulating it afterwards, fs.access()
\nis recommended.
Synchronous stat(2). Returns an instance of fs.Stats
.
Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback. The type
argument can be set to 'dir'
,\n'file'
, or 'junction'
(default is 'file'
) and is only available on\nWindows (ignored on other platforms). Note that Windows junction points require\nthe destination path to be absolute. When using 'junction'
, the target
\nargument will automatically be normalized to absolute path.
Here is an example below:
\nfs.symlink('./foo', './new-port');\n
\nIt creates a symbolic link named "new-port" that points to "foo".
\n" }, { "textRaw": "fs.symlinkSync(target, path[, type])", "type": "method", "name": "symlinkSync", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`target` {String | Buffer} ", "name": "target", "type": "String | Buffer" }, { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" }, { "textRaw": "`type` {String} ", "name": "type", "type": "String", "optional": true } ] }, { "params": [ { "name": "target" }, { "name": "path" }, { "name": "type", "optional": true } ] } ], "desc": "Synchronous symlink(2). Returns undefined
.
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.
Synchronous truncate(2). Returns undefined
. A file descriptor can also be\npassed as the first argument. In this case, fs.ftruncateSync()
is called.
Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.
\n" }, { "textRaw": "fs.unlinkSync(path)", "type": "method", "name": "unlinkSync", "meta": { "added": [ "v0.1.21" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {String | Buffer} ", "name": "path", "type": "String | Buffer" } ] }, { "params": [ { "name": "path" } ] } ], "desc": "Synchronous unlink(2). Returns undefined
.
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
.
Calling fs.unwatchFile()
with a filename that is not being watched is a\nno-op, not an error.
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.
Change file timestamps of the file referenced by the supplied path.
\nNote: the arguments atime
and mtime
of the following related functions\nfollow these rules:
Date.now()
\nreturns milliseconds, so it should be divided by 1000 before passing it in.'123456789'
, the value will get\nconverted to the corresponding number.NaN
or Infinity
, the value will get converted to\nDate.now() / 1000
.Synchronous version of fs.utimes()
. Returns undefined
.
Watch for changes on filename
, where filename
is either a file or a\ndirectory. The returned object is a fs.FSWatcher
.
The second argument is optional. If options
is provided as a string, it\nspecifies the encoding
. Otherwise options
should be passed as an object.
The listener callback gets two arguments (eventType, filename)
. eventType
is either\n'rename'
or 'change'
, and filename
is the name of the file which triggered\nthe event.
Note that on most platforms, 'rename'
is emitted whenever a filename appears\nor disappears in the directory.
Also note the listener callback is attached to the 'change'
event fired by\nfs.FSWatcher
, but it is not the same thing as the 'change'
value of\neventType
.
The fs.watch
API is not 100% consistent across platforms, and is\nunavailable in some situations.
The recursive option is only supported on OS X and Windows.
\n", "miscs": [ { "textRaw": "Availability", "name": "Availability", "type": "misc", "desc": "This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.
\ninotify
kqueue
kqueue
for files and FSEvents
for directories.event ports
.ReadDirectoryChangesW
.AHAFS
, which must be enabled.If the underlying functionality is not available for some reason, then\nfs.watch
will not be able to function. For example, watching files or\ndirectories can be unreliable, and in some cases impossible, on network file\nsystems (NFS, SMB, etc), or host file systems when using virtualization software\nsuch as Vagrant, Docker, etc.
You can still use fs.watchFile
, which uses stat polling, but it is slower and\nless reliable.
On Linux and OS X systems, fs.watch()
resolves the path to an inode and\nwatches the inode. If the watched path is deleted and recreated, it is assigned\na new inode. The watch will emit an event for the delete but will continue\nwatching the original inode. Events for the new inode will not be emitted.\nThis is expected behavior.
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.
fs.watch('somedir', (eventType, filename) => {\n console.log(`event type is: ${eventType}`);\n if (filename) {\n console.log(`filename provided: ${filename}`);\n } else {\n console.log('filename not provided');\n }\n});\n
\n"
}
]
}
]
},
{
"textRaw": "fs.watchFile(filename[, options], listener)",
"type": "method",
"name": "watchFile",
"meta": {
"added": [
"v0.1.31"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`filename` {String | Buffer} ",
"name": "filename",
"type": "String | Buffer"
},
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`persistent` {Boolean} ",
"name": "persistent",
"type": "Boolean"
},
{
"textRaw": "`interval` {Integer} ",
"name": "interval",
"type": "Integer"
}
],
"name": "options",
"type": "Object",
"optional": true
},
{
"textRaw": "`listener` {Function} ",
"name": "listener",
"type": "Function"
}
]
},
{
"params": [
{
"name": "filename"
},
{
"name": "options",
"optional": true
},
{
"name": "listener"
}
]
}
],
"desc": "Watch for changes on filename
. The callback listener
will be called each\ntime the file is accessed.
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 }
.
The listener
gets two arguments the current stat object and the previous\nstat object:
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
\nThese stat objects are instances of fs.Stat
.
If you want to be notified when the file was modified, not just accessed,\nyou need to compare curr.mtime
and prev.mtime
.
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.
Note: fs.watch()
is more efficient than fs.watchFile
and\nfs.unwatchFile
. fs.watch
should be used instead of fs.watchFile
and\nfs.unwatchFile
when possible.
Write buffer
to the file specified by fd
.
offset
determines the part of the buffer to be written, and length
is\nan integer specifying the number of bytes to write.
position
refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number'
, the data will be written\nat the current position. See pwrite(2).
The callback will be given three arguments (err, written, buffer)
where\nwritten
specifies how many bytes were written from buffer
.
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.
On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
\n" }, { "textRaw": "fs.write(fd, string[, position[, encoding]], callback)", "type": "method", "name": "write", "meta": { "added": [ "v0.11.5" ] }, "signatures": [ { "params": [ { "textRaw": "`fd` {Integer} ", "name": "fd", "type": "Integer" }, { "textRaw": "`string` {String} ", "name": "string", "type": "String" }, { "textRaw": "`position` {Integer} ", "name": "position", "type": "Integer", "optional": true }, { "textRaw": "`encoding` {String} ", "name": "encoding", "type": "String", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "fd" }, { "name": "string" }, { "name": "position", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback" } ] } ], "desc": "Write string
to the file specified by fd
. If string
is not a string, then\nthe value will be coerced to one.
position
refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number'
the data will be written at\nthe current position. See pwrite(2).
encoding
is the expected string encoding.
The callback will receive the arguments (err, written, string)
where written
\nspecifies how many bytes the passed string required to be written. Note that\nbytes written is not the same as string characters. See Buffer.byteLength
.
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.
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.
On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
\n" }, { "textRaw": "fs.writeFile(file, data[, options], callback)", "type": "method", "name": "writeFile", "meta": { "added": [ "v0.1.29" ] }, "signatures": [ { "params": [ { "textRaw": "`file` {String | Buffer | Integer} filename or file descriptor ", "name": "file", "type": "String | Buffer | Integer", "desc": "filename or file descriptor" }, { "textRaw": "`data` {String | Buffer | Uint8Array} ", "name": "data", "type": "String | Buffer | Uint8Array" }, { "textRaw": "`options` {Object | String} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `'utf8'` ", "name": "encoding", "type": "String | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {Integer} default = `0o666` ", "name": "mode", "type": "Integer", "desc": "default = `0o666`" }, { "textRaw": "`flag` {String} default = `'w'` ", "name": "flag", "type": "String", "desc": "default = `'w'`" } ], "name": "options", "type": "Object | String", "optional": true }, { "textRaw": "`callback` {Function} ", "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.
The encoding
option is ignored if data
is a buffer. It defaults\nto 'utf8'
.
Example:
\nfs.writeFile('message.txt', 'Hello Node.js', (err) => {\n if (err) throw err;\n console.log('It\\'s saved!');\n});\n
\nIf options
is a string, then it specifies the encoding. Example:
fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);\n
\nAny specified file descriptor has to support writing.
\nNote 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.
Note: If a file descriptor is specified as the file
, it will not be closed\nautomatically.
The synchronous version of fs.writeFile()
. Returns undefined
.
Synchronous versions of fs.write()
. Returns the number of bytes written.
Synchronous versions of fs.write()
. Returns the number of bytes written.
Returns an object containing commonly used constants for file system\noperations. The specific constants currently defined are described in\nFS Constants.
\n" } ], "type": "module", "displayName": "fs" }, { "textRaw": "HTTP", "name": "http", "stability": 2, "stabilityText": "Stable", "desc": "To use the HTTP server and client one must require('http')
.
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.
\nHTTP message headers are represented by an object like this:
\n{ 'content-length': '123',\n 'content-type': 'text/plain',\n 'connection': 'keep-alive',\n 'host': 'mysite.com',\n 'accept': '*/*' }\n
\nKeys are lowercased. Values are not modified.
\nIn 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.
\nSee message.headers
for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders
\nproperty, which is an array of [key, value, key2, value2, ...]
. For\nexample, the previous message header object might have a rawHeaders
\nlist like the following:
[ 'ConTent-Length', '123456',\n 'content-LENGTH', '123',\n 'content-type', 'text/plain',\n 'CONNECTION', 'keep-alive',\n 'Host', 'mysite.com',\n 'accepT', '*/*' ]\n
\n",
"classes": [
{
"textRaw": "Class: http.Agent",
"type": "class",
"name": "http.Agent",
"meta": {
"added": [
"v0.3.4"
]
},
"desc": "An Agent
is responsible for managing connection persistence\nand reuse for HTTP clients. It maintains a queue of pending requests\nfor a given host and port, reusing a single socket connection for each\nuntil the queue is empty, at which time the socket is either destroyed\nor put into a pool where it is kept to be used again for requests to the\nsame host and port. Whether it is destroyed or pooled depends on the\nkeepAlive
option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may\nstill close idle connections, in which case they will be removed from the\npool and a new connection will be made when a new HTTP request is made for\nthat host and port. Servers may also refuse to allow multiple requests\nover the same connection, in which case the connection will have to be\nremade for every request and cannot be pooled. The Agent
will still make\nthe requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed\nfrom the pool. Any unused sockets in the pool will be unrefed so as not\nto keep the Node.js process running when there are no outstanding requests.\n(see socket.unref()).
\nIt is good practice, to destroy()
an Agent
instance when it is no\nlonger in use, because unused sockets consume OS resources.
Sockets are removed from an agent's pool when the socket emits either\na 'close'
event or an 'agentRemove'
event. This means that if\nyou intend to keep one HTTP request open for a long time and don't\nwant it to stay in the pool you can do something along the lines of:
http.get(options, (res) => {\n // Do stuff\n}).on('socket', (socket) => {\n socket.emit('agentRemove');\n});\n
\nYou may also use an agent for an individual request. By providing\n{agent: false}
as an option to the http.get()
or http.request()
\nfunctions, a one-time use Agent
with default options will be used\nfor the client connection.
agent:false
:
http.get({\n hostname: 'localhost',\n port: 80,\n path: '/',\n agent: false // create a new agent just for this one request\n}, (res) => {\n // Do stuff with response\n});\n
\n",
"methods": [
{
"textRaw": "agent.createConnection(options[, callback])",
"type": "method",
"name": "createConnection",
"meta": {
"added": [
"v0.11.4"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {net.Socket} ",
"name": "return",
"type": "net.Socket"
},
"params": [
{
"textRaw": "`options` {Object} Options containing connection details. Check [`net.createConnection()`][] for the format of the options ",
"name": "options",
"type": "Object",
"desc": "Options containing connection details. Check [`net.createConnection()`][] for the format of the options"
},
{
"textRaw": "`callback` {Function} Callback function that receives the created socket ",
"name": "callback",
"type": "Function",
"desc": "Callback function that receives the created socket",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Produces a socket/stream to be used for HTTP requests.
\nBy default, this function is the same as net.createConnection()
. However,\ncustom agents may override this method in case greater flexibility is desired.
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
.
callback
has a signature of (err, stream)
.
Destroy any sockets that are currently in use by the agent.
\nIt 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.
Get a unique name for a set of request options, to determine whether a\nconnection can be reused. For an HTTP agent, this returns\nhost:port:localAddress
. For an HTTPS agent, the name includes the\nCA, cert, ciphers, and other HTTPS/TLS-specific options that determine\nsocket reusability.
An object which contains arrays of sockets currently awaiting use by\nthe agent when keepAlive
is enabled. Do not modify.
By default set to 256. For agents with keepAlive
enabled, this\nsets the maximum number of sockets that will be left open in the free\nstate.
By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open per origin. Origin is either a 'host:port' or\n'host:port:localAddress' combination.
\n" }, { "textRaw": "`requests` {Object} ", "type": "Object", "name": "requests", "meta": { "added": [ "v0.5.9" ] }, "desc": "An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.
\n" }, { "textRaw": "`sockets` {Object} ", "type": "Object", "name": "sockets", "meta": { "added": [ "v0.3.6" ] }, "desc": "An object which contains arrays of sockets currently in use by the\nagent. Do not modify.
\n" } ], "signatures": [ { "params": [ { "textRaw": "`options` {Object} Set of configurable options to set on the agent. Can have the following fields: ", "options": [ { "textRaw": "`keepAlive` {Boolean} Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Default = `false` ", "name": "keepAlive", "type": "Boolean", "desc": "Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Default = `false`" }, { "textRaw": "`keepAliveMsecs` {Integer} When using the `keepAlive` option, specifies the [initial delay](#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. Default = `1000`. ", "name": "keepAliveMsecs", "type": "Integer", "desc": "When using the `keepAlive` option, specifies the [initial delay](#net_socket_setkeepalive_enable_initialdelay) for TCP Keep-Alive packets. Ignored when the `keepAlive` option is `false` or `undefined`. Default = `1000`." }, { "textRaw": "`maxSockets` {Number} Maximum number of sockets to allow per host. Default = `Infinity`. ", "name": "maxSockets", "type": "Number", "desc": "Maximum number of sockets to allow per host. Default = `Infinity`." }, { "textRaw": "`maxFreeSockets` {Number} Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`. Default = `256`. ", "name": "maxFreeSockets", "type": "Number", "desc": "Maximum number of sockets to leave open in a free state. Only relevant if `keepAlive` is set to `true`. Default = `256`." } ], "name": "options", "type": "Object", "desc": "Set of configurable options to set on the agent. Can have the following fields:", "optional": true } ], "desc": "The default http.globalAgent
that is used by http.request()
has all\nof these values set to their respective defaults.
To configure any of them, you must create your own http.Agent
instance.
const http = require('http');\nvar keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
\n"
},
{
"params": [
{
"name": "options",
"optional": true
}
],
"desc": "The default http.globalAgent
that is used by http.request()
has all\nof these values set to their respective defaults.
To configure any of them, you must create your own http.Agent
instance.
const http = require('http');\nvar keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n
\n"
}
]
},
{
"textRaw": "Class: http.ClientRequest",
"type": "class",
"name": "http.ClientRequest",
"meta": {
"added": [
"v0.1.17"
]
},
"desc": "This object is created internally and returned from http.request()
. It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value)
, getHeader(name)
,\nremoveHeader(name)
API. The actual header will be sent along with the first\ndata chunk or when closing the connection.
To get the response, add a listener for 'response'
to the request object.\n'response'
will be emitted from the request object when the response\nheaders have been received. The 'response'
event is executed with one\nargument which is an instance of http.IncomingMessage
.
During the 'response'
event, one can add listeners to the\nresponse object; particularly to listen for the 'data'
event.
If no 'response'
handler is added, then the response will be\nentirely discarded. However, if 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.
Note: Node.js does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.
\nThe request implements the Writable Stream interface. This is an\nEventEmitter
with the following events:
Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort()
.
Emitted when the request has been aborted by the server and the network\nsocket has closed.
\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "Emitted each time a server responds to a request with a CONNECT
method. If this\nevent is not being listened for, clients receiving a CONNECT
method will have\ntheir connections closed.
A client and server pair that shows you how to listen for the 'connect'
event:
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
\n"
},
{
"textRaw": "Event: 'continue'",
"type": "event",
"name": "continue",
"meta": {
"added": [
"v0.3.2"
]
},
"desc": "Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.
\n", "params": [] }, { "textRaw": "Event: 'response'", "type": "event", "name": "response", "meta": { "added": [ "v0.1.0" ] }, "params": [], "desc": "Emitted when a response is received to this request. This event is emitted only\nonce.
\n" }, { "textRaw": "Event: 'socket'", "type": "event", "name": "socket", "meta": { "added": [ "v0.5.3" ] }, "params": [], "desc": "Emitted after a socket is assigned to this request.
\n" }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ] }, "params": [], "desc": "Emitted each time a server responds to a request with an upgrade. If this\nevent is not being listened for, clients receiving an upgrade header will have\ntheir connections closed.
\nA client server pair that show you how to listen for the 'upgrade'
event.
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
\n"
}
],
"methods": [
{
"textRaw": "request.abort()",
"type": "method",
"name": "abort",
"meta": {
"added": [
"v0.3.8"
]
},
"desc": "Marks the request as aborting. Calling this will cause remaining data\nin the response to be dropped and the socket to be destroyed.
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.end([data][, encoding][, callback])", "type": "method", "name": "end", "meta": { "added": [ "v0.1.90" ] }, "signatures": [ { "params": [ { "textRaw": "`data` {String | Buffer} ", "name": "data", "type": "String | Buffer", "optional": true }, { "textRaw": "`encoding` {String} ", "name": "encoding", "type": "String", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'
.
If data
is specified, it is equivalent to calling\nresponse.write(data, encoding)
followed by request.end(callback)
.
If callback
is specified, it will be called when the request stream\nis finished.
Flush the request headers.
\nFor 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.
That's usually what you want (it saves a TCP round-trip) but not when the first\ndata is not sent until possibly much later. request.flushHeaders()
lets you bypass\nthe optimization and kickstart the request.
Once a socket is assigned to this request and is connected\nsocket.setNoDelay()
will be called.
Once a socket is assigned to this request and is connected\nsocket.setKeepAlive()
will be called.
Once a socket is assigned to this request and is connected\nsocket.setTimeout()
will be called.
Returns request
.
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.
The encoding
argument is optional and only applies when chunk
is a string.\nDefaults to 'utf8'
.
The callback
argument is optional and will be called when this chunk of data\nis flushed.
Returns request
.
This class inherits from net.Server
and has the following additional events:
Emitted each time a request with an HTTP Expect: 100-continue
is received.\nIf this event is not listened for, the server will automatically respond\nwith a 100 Continue
as appropriate.
Handling this event involves calling response.writeContinue()
if the 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.
Note that when this event is emitted and handled, the 'request'
event will\nnot be emitted.
Emitted each time a request with an HTTP Expect
header is received, where the\nvalue is not 100-continue
. If this event is not listened for, the server will\nautomatically respond with a 417 Expectation Failed
as appropriate.
Note that when this event is emitted and handled, the 'request'
event will\nnot be emitted.
If a client connection emits an 'error'
event, it will be forwarded here.\nListener of this event is responsible for closing/destroying the underlying\nsocket. For example, one may wish to more gracefully close the socket with an\nHTTP '400 Bad Request' response instead of abruptly severing the connection.
Default behavior is to destroy the socket immediately on malformed request.
\nsocket
is the net.Socket
object that the error originated from.
const http = require('http');\n\nconst server = http.createServer((req, res) => {\n res.end();\n});\nserver.on('clientError', (err, socket) => {\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\nserver.listen(8000);\n
\nWhen the 'clientError'
event occurs, there is no request
or response
\nobject, so any HTTP response sent, including response headers and payload,\nmust be written directly to the socket
object. Care must be taken to\nensure the response is a properly formatted HTTP response message.
Emitted when the server closes.
\n", "params": [] }, { "textRaw": "Event: 'connect'", "type": "event", "name": "connect", "meta": { "added": [ "v0.7.0" ] }, "params": [], "desc": "Emitted each time a client requests an HTTP CONNECT
method. If this event is\nnot listened for, then clients requesting a CONNECT
method will have their\nconnections closed.
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.
When a new TCP stream is established. socket
is an object of type\nnet.Socket
. Usually users will not want to access this event. In\nparticular, the socket will not emit 'readable'
events because of how\nthe protocol parser attaches to the socket. The socket
can also be\naccessed at request.connection
.
Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of HTTP Keep-Alive connections).
\n" }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "meta": { "added": [ "v0.1.94" ] }, "params": [], "desc": "Emitted each time a client requests an HTTP upgrade. If this event is not\nlistened for, then clients requesting an upgrade will have their connections\nclosed.
\nAfter 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.
Stops the server from accepting new connections. See net.Server.close()
.
The handle
object can be set to either a server or socket (anything\nwith an underlying _handle
member), or a {fd: <n>}
object.
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.
\nListening on a file descriptor is not supported on Windows.
\nThis function is asynchronous. callback
will be added as a listener for the\n'listening'
event. See also net.Server.listen()
.
Returns server
.
Note: The server.listen()
method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.
Start a UNIX socket server listening for connections on the given path
.
This function is asynchronous. callback
will be added as a listener for the\n'listening'
event. See also net.Server.listen(path)
.
Note: The server.listen()
method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.
Begin accepting connections on the specified port
and hostname
. If the\nhostname
is omitted, the server will accept connections on any IPv6 address\n(::
) when IPv6 is available, or any IPv4 address (0.0.0.0
) otherwise.\nOmit the port argument, or use a port value of 0
, to have the operating system\nassign a random port, which can be retrieved by using server.address().port
\nafter the 'listening'
event has been emitted.
To listen to a unix socket, supply a filename instead of port and hostname.
\nbacklog
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).
This function is asynchronous. callback
will be added as a listener for the\n'listening'
event. See also net.Server.listen(port)
.
Note: The server.listen()
method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.
Sets the timeout value for sockets, and emits a 'timeout'
event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.
If there is a 'timeout'
event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.
By default, the Server'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.
Returns server
.
A Boolean indicating whether or not the server is listening for\nconnections.
\n" }, { "textRaw": "`maxHeadersCount` {Number} ", "type": "Number", "name": "maxHeadersCount", "meta": { "added": [ "v0.7.0" ] }, "desc": "Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.
\n" }, { "textRaw": "`timeout` {Number} Default = 120000 (2 minutes) ", "type": "Number", "name": "timeout", "meta": { "added": [ "v0.9.12" ] }, "desc": "The number of milliseconds of inactivity before a socket is presumed\nto have timed out.
\nNote 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.
\nSet to 0 to disable any kind of automatic timeout behavior on incoming\nconnections.
\n", "shortDesc": "Default = 120000 (2 minutes)" } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "meta": { "added": [ "v0.1.17" ] }, "desc": "This object is created internally by an HTTP server--not by the user. It is\npassed as the second parameter to the 'request'
event.
The response implements, but does not inherit from, the Writable Stream\ninterface. This is an EventEmitter
with the following events:
Indicates that the underlying connection was terminated before\nresponse.end()
was called or able to flush.
Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.
\nAfter this event, no more events will be emitted on the response object.
\n", "params": [] } ], "methods": [ { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "meta": { "added": [ "v0.3.0" ] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object} ", "name": "headers", "type": "Object" } ] }, { "params": [ { "name": "headers" } ] } ], "desc": "This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.
\nTrailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g. if the request was HTTP/1.0), they will\nbe silently discarded.
\nNote 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.,
response.writeHead(200, { 'Content-Type': 'text/plain',\n 'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});\nresponse.end();\n
\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end()
, MUST be called on each response.
If data
is specified, it is equivalent to calling\nresponse.write(data, encoding)
followed by response.end(callback)
.
If callback
is specified, it will be called when the response stream\nis finished.
Reads out a header that's already been queued but not sent to the client.\nNote that the name is case insensitive.
\nExample:
\nvar contentType = response.getHeader('content-type');\n
\n"
},
{
"textRaw": "response.removeHeader(name)",
"type": "method",
"name": "removeHeader",
"meta": {
"added": [
"v0.4.0"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {String} ",
"name": "name",
"type": "String"
}
]
},
{
"params": [
{
"name": "name"
}
]
}
],
"desc": "Removes a header that's queued for implicit sending.
\nExample:
\nresponse.removeHeader('Content-Encoding');\n
\n"
},
{
"textRaw": "response.setHeader(name, value)",
"type": "method",
"name": "setHeader",
"meta": {
"added": [
"v0.4.0"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {String} ",
"name": "name",
"type": "String"
},
{
"textRaw": "`value` {String} ",
"name": "value",
"type": "String"
}
]
},
{
"params": [
{
"name": "name"
},
{
"name": "value"
}
]
}
],
"desc": "Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere if you need to send multiple headers with the same name.
\nExample:
\nresponse.setHeader('Content-Type', 'text/html');\n
\nor
\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n
\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
When headers have been set with response.setHeader()
, they will be merged with\nany headers passed to response.writeHead()
, with the headers passed to\nresponse.writeHead()
given precedence.
// returns content-type = text/plain\nconst server = http.createServer((req,res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, {'Content-Type': 'text/plain'});\n res.end('ok');\n});\n
\n"
},
{
"textRaw": "response.setTimeout(msecs, callback)",
"type": "method",
"name": "setTimeout",
"meta": {
"added": [
"v0.9.12"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`msecs` {Number} ",
"name": "msecs",
"type": "Number"
},
{
"textRaw": "`callback` {Function} ",
"name": "callback",
"type": "Function"
}
]
},
{
"params": [
{
"name": "msecs"
},
{
"name": "callback"
}
]
}
],
"desc": "Sets the Socket's timeout value to msecs
. If a callback is\nprovided, then it is added as a listener on the 'timeout'
event on\nthe response object.
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.
Returns response
.
If this method is called and response.writeHead()
has not been called,\nit will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.
\nchunk
can be a string or a buffer. If chunk
is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding
is 'utf8'
. callback
will be called when this chunk\nof data is flushed.
Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.
\nThe first time response.write()
is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write()
is called, Node.js assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of body.
Returns true
if the entire data was flushed successfully to the kernel\nbuffer. Returns false
if all or part of the data was queued in user memory.\n'drain'
will be emitted when the buffer is free again.
Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the 'checkContinue'
event on Server
.
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.
Example:
\nvar body = 'hello world';\nresponse.writeHead(200, {\n 'Content-Length': Buffer.byteLength(body),\n 'Content-Type': 'text/plain' });\n
\nThis method must only be called once on a message and it must\nbe called before response.end()
is called.
If you call response.write()
or response.end()
before calling this,\nthe implicit/mutable headers will be calculated and call this function for you.
When headers have been set with response.setHeader()
, they will be merged with\nany headers passed to response.writeHead()
, with the headers passed to\nresponse.writeHead()
given precedence.
// 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
\nNote 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.
Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError
being thrown.
Boolean value that indicates whether the response has completed. Starts\nas false
. After response.end()
executes, the value will be true
.
Boolean (read-only). True if headers were sent, false otherwise.
\n" }, { "textRaw": "`sendDate` {Boolean} ", "type": "Boolean", "name": "sendDate", "meta": { "added": [ "v0.7.5" ] }, "desc": "When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.
\nThis should only be disabled for testing; HTTP requires the Date header\nin responses.
\n" }, { "textRaw": "`statusCode` {Number} ", "type": "Number", "name": "statusCode", "meta": { "added": [ "v0.4.0" ] }, "desc": "When using implicit headers (not calling response.writeHead()
explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.
Example:
\nresponse.statusCode = 404;\n
\nAfter response header was sent to the client, this property indicates the\nstatus code which was sent out.
\n" }, { "textRaw": "`statusMessage` {String} ", "type": "String", "name": "statusMessage", "meta": { "added": [ "v0.11.8" ] }, "desc": "When using implicit headers (not calling response.writeHead()
explicitly), this property\ncontrols the status message that will be sent to the client when the headers get\nflushed. If this is left as undefined
then the standard message for the status\ncode will be used.
Example:
\nresponse.statusMessage = 'Not found';\n
\nAfter response header was sent to the client, this property indicates the\nstatus message which was sent out.
\n" } ] }, { "textRaw": "Class: http.IncomingMessage", "type": "class", "name": "http.IncomingMessage", "meta": { "added": [ "v0.1.17" ] }, "desc": "An IncomingMessage
object is created by http.Server
or\nhttp.ClientRequest
and passed as the first argument to the 'request'
\nand 'response'
event respectively. It may be used to access response status,\nheaders and data.
It implements the Readable Stream interface, as well as the\nfollowing additional events, methods, and properties.
\n", "events": [ { "textRaw": "Event: 'aborted'", "type": "event", "name": "aborted", "meta": { "added": [ "v0.3.8" ] }, "desc": "Emitted when the request has been aborted by the client and the network\nsocket has closed.
\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "meta": { "added": [ "v0.4.2" ] }, "desc": "Indicates that the underlying connection was closed.\nJust like 'end'
, this event occurs only once per response.
Calls destroy()
on the socket that received the IncomingMessage
. If error
\nis provided, an 'error'
event is emitted and error
is passed as an argument\nto any listeners on the event.
Calls message.connection.setTimeout(msecs, callback)
.
Returns message
.
The request/response headers object.
\nKey-value pairs of header names and values. Header names are lower-cased.\nExample:
\n// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n// host: '127.0.0.1:8000',\n// accept: '*/*' }\nconsole.log(request.headers);\n
\nDuplicates in raw headers are handled in the following ways, depending on the\nheader name:
\nage
, authorization
, content-length
, content-type
,\netag
, expires
, from
, host
, if-modified-since
, if-unmodified-since
,\nlast-modified
, location
, max-forwards
, proxy-authorization
, referer
,\nretry-after
, or user-agent
are discarded.set-cookie
is always an array. Duplicates are added to the array.In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1'
or '1.0'
.
Also message.httpVersionMajor
is the first integer and\nmessage.httpVersionMinor
is the second.
Only valid for request obtained from http.Server
.
The request method as a string. Read only. Example:\n'GET'
, 'DELETE'
.
The raw request/response headers list exactly as they were received.
\nNote 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.
\nHeader names are not lowercased, and duplicates are not merged.
\n// Prints something like:\n//\n// [ 'user-agent',\n// 'this is invalid because there can be only one',\n// 'User-Agent',\n// 'curl/7.22.0',\n// 'Host',\n// '127.0.0.1:8000',\n// 'ACCEPT',\n// '*/*' ]\nconsole.log(request.rawHeaders);\n
\n"
},
{
"textRaw": "`rawTrailers` {Array} ",
"type": "Array",
"name": "rawTrailers",
"meta": {
"added": [
"v0.11.6"
]
},
"desc": "The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end'
event.
Only valid for response obtained from http.ClientRequest
.
The 3-digit HTTP response status code. E.G. 404
.
Only valid for response obtained from http.ClientRequest
.
The HTTP response status message (reason phrase). E.G. OK
or Internal Server Error
.
The net.Socket
object associated with the connection.
With HTTPS support, use request.socket.getPeerCertificate()
to obtain the\nclient's authentication details.
The request/response trailers object. Only populated at the 'end'
event.
Only valid for request obtained from http.Server
.
Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:
\nGET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n\n
\nThen request.url
will be:
'/status?name=ryan'\n
\nIf you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url)
. Example:
$ 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
\nIf you would like to extract the parameters from the query string,\nyou can use the require('querystring').parse
function, or pass\ntrue
as the second argument to require('url').parse
. Example:
$ node\n> require('url').parse('/status?name=ryan', true)\n{\n href: '/status?name=ryan',\n search: '?name=ryan',\n query: {name: 'ryan'},\n pathname: '/status'\n}\n
\n"
}
]
}
],
"properties": [
{
"textRaw": "`METHODS` {Array} ",
"type": "Array",
"name": "METHODS",
"meta": {
"added": [
"v0.11.8"
]
},
"desc": "A list of the HTTP methods that are supported by the parser.
\n" }, { "textRaw": "`STATUS_CODES` {Object} ", "type": "Object", "name": "STATUS_CODES", "meta": { "added": [ "v0.1.22" ] }, "desc": "A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'
.
Global instance of Agent
which is used as the default for all HTTP client\nrequests.
Returns a new instance of http.Server
.
The requestListener
is a function which is automatically\nadded to the 'request'
event.
Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and\nhttp.request()
is that it sets the method to GET and calls req.end()
\nautomatically. Note that response data must be consumed in the callback\nfor reasons stated in http.ClientRequest
section.
The callback
is invoked with a single argument that is an instance of\nhttp.IncomingMessage
JSON Fetching Example:
\nhttp.get('http://nodejs.org/dist/index.json', (res) => {\n const statusCode = res.statusCode;\n const contentType = res.headers['content-type'];\n\n let error;\n if (statusCode !== 200) {\n error = new Error(`Request Failed.\\n` +\n `Status Code: ${statusCode}`);\n } else if (!/^application\\/json/.test(contentType)) {\n error = new Error(`Invalid content-type.\\n` +\n `Expected application/json but received ${contentType}`);\n }\n if (error) {\n console.log(error.message);\n // consume response data to free up memory\n res.resume();\n return;\n }\n\n res.setEncoding('utf8');\n let rawData = '';\n res.on('data', (chunk) => rawData += chunk);\n res.on('end', () => {\n try {\n let parsedData = JSON.parse(rawData);\n console.log(parsedData);\n } catch (e) {\n console.log(e.message);\n }\n });\n}).on('error', (e) => {\n console.log(`Got error: ${e.message}`);\n});\n
\n"
},
{
"textRaw": "http.request(options[, callback])",
"type": "method",
"name": "request",
"meta": {
"added": [
"v0.3.6"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {http.ClientRequest} ",
"name": "return",
"type": "http.ClientRequest"
},
"params": [
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`protocol` {String} Protocol to use. Defaults to `'http:'`. ",
"name": "protocol",
"type": "String",
"desc": "Protocol to use. Defaults to `'http:'`."
},
{
"textRaw": "`host` {String} A domain name or IP address of the server to issue the request to. Defaults to `'localhost'`. ",
"name": "host",
"type": "String",
"desc": "A domain name or IP address of the server to issue the request to. Defaults to `'localhost'`."
},
{
"textRaw": "`hostname` {String} Alias for `host`. To support [`url.parse()`][], `hostname` is preferred over `host`. ",
"name": "hostname",
"type": "String",
"desc": "Alias for `host`. To support [`url.parse()`][], `hostname` is preferred over `host`."
},
{
"textRaw": "`family` {Number} IP address family to use when resolving `host` and `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used. ",
"name": "family",
"type": "Number",
"desc": "IP address family to use when resolving `host` and `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used."
},
{
"textRaw": "`port` {Number} Port of remote server. Defaults to 80. ",
"name": "port",
"type": "Number",
"desc": "Port of remote server. Defaults to 80."
},
{
"textRaw": "`localAddress` {String} Local interface to bind for network connections. ",
"name": "localAddress",
"type": "String",
"desc": "Local interface to bind for network connections."
},
{
"textRaw": "`socketPath` {String} Unix Domain Socket (use one of host:port or socketPath). ",
"name": "socketPath",
"type": "String",
"desc": "Unix Domain Socket (use one of host:port or socketPath)."
},
{
"textRaw": "`method` {String} A string specifying the HTTP request method. Defaults to `'GET'`. ",
"name": "method",
"type": "String",
"desc": "A string specifying the HTTP request method. Defaults to `'GET'`."
},
{
"textRaw": "`path` {String} Request path. Defaults to `'/'`. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. ",
"name": "path",
"type": "String",
"desc": "Request path. Defaults to `'/'`. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future."
},
{
"textRaw": "`headers` {Object} An object containing request headers. ",
"name": "headers",
"type": "Object",
"desc": "An object containing request headers."
},
{
"textRaw": "`auth` {String} Basic authentication i.e. `'user:password'` to compute an Authorization header. ",
"name": "auth",
"type": "String",
"desc": "Basic authentication i.e. `'user:password'` to compute an Authorization header."
},
{
"textRaw": "`agent` {http.Agent|Boolean} Controls [`Agent`][] behavior. Possible values: ",
"options": [
{
"textRaw": "`undefined` (default): use [`http.globalAgent`][] for this host and port. ",
"name": "undefined",
"default": "",
"desc": ": use [`http.globalAgent`][] for this host and port."
},
{
"textRaw": "`Agent` object: explicitly use the passed in `Agent`. ",
"name": "Agent",
"desc": "object: explicitly use the passed in `Agent`."
},
{
"textRaw": "`false`: causes a new `Agent` with default values to be used. ",
"name": "false",
"desc": "causes a new `Agent` with default values to be used."
}
],
"name": "agent",
"type": "http.Agent|Boolean",
"desc": "Controls [`Agent`][] behavior. Possible values:"
},
{
"textRaw": "`createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details. ",
"name": "createConnection",
"type": "Function",
"desc": "A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See [`agent.createConnection()`][] for more details."
},
{
"textRaw": "`timeout` {Integer}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected. ",
"name": "timeout",
"type": "Integer",
"desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected."
}
],
"name": "options",
"type": "Object"
},
{
"textRaw": "`callback` {Function} ",
"name": "callback",
"type": "Function",
"optional": true
}
]
},
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.
\noptions
can be an object or a string. If options
is a string, it is\nautomatically parsed with url.parse()
.
The optional callback
parameter will be added as a one time listener for\nthe 'response'
event.
http.request()
returns an instance of the http.ClientRequest
\nclass. The ClientRequest
instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest
object.
Example:
\nvar 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': Buffer.byteLength(postData)\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
\nNote 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.
If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error'
event is emitted\non the returned request object. As with all 'error'
events, if no listeners\nare registered the error will be thrown.
There are a few special headers that should be noted.
\nSending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.
\nSending a 'Content-Length' header will disable the default chunked encoding.
\nSending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', you should both set a timeout\nand listen for the 'continue'
event. See RFC2616 Section 8.2.3 for more\ninformation.
Sending an Authorization header will override using the auth
option\nto compute basic authentication.
HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a\nseparate module.
\n", "classes": [ { "textRaw": "Class: https.Agent", "type": "class", "name": "https.Agent", "meta": { "added": [ "v0.4.5" ] }, "desc": "An Agent object for HTTPS similar to http.Agent
. See https.request()
\nfor more information.
This class is a subclass of tls.Server
and emits events same as\nhttp.Server
. See http.Server
for more information.
See http.Server#timeout
.
Returns a new HTTPS web server object. The options
is similar to\ntls.createServer()
. The requestListener
is a function which is\nautomatically added to the 'request'
event.
Example:
\n// curl -k https://localhost:8000/\nconst https = require('https');\nconst fs = require('fs');\n\nconst options = {\n key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\n\nhttps.createServer(options, (req, res) => {\n res.writeHead(200);\n res.end('hello world\\n');\n}).listen(8000);\n
\nOr
\nconst 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
\n",
"methods": [
{
"textRaw": "server.close([callback])",
"type": "method",
"name": "close",
"meta": {
"added": [
"v0.1.90"
]
},
"desc": "See http.close()
for details.
See http.listen()
for details.
See http.listen()
for details.
Like http.get()
but for HTTPS.
options
can be an object or a string. If options
is a string, it is\nautomatically parsed with url.parse()
.
Example:
\nconst https = require('https');\n\nhttps.get('https://encrypted.google.com/', (res) => {\n console.log('statusCode:', res.statusCode);\n console.log('headers:', res.headers);\n\n res.on('data', (d) => {\n process.stdout.write(d);\n });\n\n}).on('error', (e) => {\n console.error(e);\n});\n
\n",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "https.request(options, callback)",
"type": "method",
"name": "request",
"meta": {
"added": [
"v0.3.6"
]
},
"desc": "Makes a request to a secure web server.
\noptions
can be an object or a string. If options
is a string, it is\nautomatically parsed with url.parse()
.
All options from http.request()
are valid.
Example:
\nconst 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});\n\nreq.on('error', (e) => {\n console.error(e);\n});\nreq.end();\n
\nThe options argument has the following options
\nhost
: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'
.hostname
: Alias for host
. To support url.parse()
hostname
is\npreferred over host
.family
: IP address family to use when resolving host
and hostname
.\nValid values are 4
or 6
. When unspecified, both IP v4 and v6 will be\nused.port
: Port of remote server. Defaults to 443.localAddress
: Local interface to bind for network connections.socketPath
: Unix Domain Socket (use one of host:port or socketPath).method
: A string specifying the HTTP request method. Defaults to 'GET'
.path
: Request path. Defaults to '/'
. Should include query string if any.\nE.G. '/index.html?page=12'
. An exception is thrown when the request path\ncontains illegal characters. Currently, only spaces are rejected but that\nmay change in the future.headers
: An object containing request headers.auth
: Basic authentication i.e. 'user:password'
to compute an\nAuthorization header.agent
: Controls Agent
behavior. When an Agent is used request will\ndefault to Connection: keep-alive
. Possible values:undefined
(default): use globalAgent
for this host and port.Agent
object: explicitly use the passed in Agent
.false
: opts out of connection pooling with an Agent, defaults request to\nConnection: close
.The following options from tls.connect()
can also be specified:
pfx
: Certificate, Private key and CA certificates to use for SSL. Default null
.key
: Private key to use for SSL. Default null
.passphrase
: A string of passphrase for the private key or pfx. Default null
.cert
: Public x509 certificate to use. Default null
.ca
: A string, Buffer
or array of strings or Buffer
s of trusted\ncertificates in PEM format. If this is omitted several well known "root"\nCAs will be used, like VeriSign. These are used to authorize connections.ciphers
: A string describing the ciphers to use or exclude. Consult\nhttps://www.openssl.org/docs/man1.0.2/apps/ciphers.html#CIPHER-LIST-FORMAT for\ndetails on the format.rejectUnauthorized
: If true
, the server certificate is verified against\nthe list of supplied CAs. An 'error'
event is emitted if verification\nfails. Verification happens at the connection level, before the HTTP\nrequest is sent. Default true
.secureProtocol
: The SSL method to use, e.g. SSLv3_method
to force\nSSL version 3. The possible values depend on your installation of\nOpenSSL and are defined in the constant SSL_METHODS
.servername
: Servername for SNI (Server Name Indication) TLS extension.In order to specify these options, use a custom Agent
.
Example:
\nvar 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
\nAlternatively, opt out of connection pooling by not using an Agent
.
Example:
\nvar 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
\n\n\n",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "callback"
}
]
}
]
}
],
"properties": [
{
"textRaw": "https.globalAgent",
"name": "globalAgent",
"meta": {
"added": [
"v0.5.9"
]
},
"desc": "Global instance of https.Agent
for all HTTPS client requests.
Node.js has a simple module loading system. In Node.js, files and modules\nare in one-to-one correspondence (each file is treated as a separate module).
\nAs an example, consider a file named foo.js
:
const circle = require('./circle.js');\nconsole.log(`The area of a circle of radius 4 is ${circle.area(4)}`);\n
\nOn the first line, foo.js
loads the module circle.js
that is in the same\ndirectory as foo.js
.
Here are the contents of circle.js
:
const PI = Math.PI;\n\nexports.area = (r) => PI * r * r;\n\nexports.circumference = (r) => 2 * PI * r;\n
\nThe 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.
Variables local to the module will be private, because the module is wrapped\nin a function by Node.js (see module wrapper).\nIn this example, the variable PI
is private to circle.js
.
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
.
Below, bar.js
makes use of the square
module, which exports a constructor:
const square = require('./square.js');\nvar mySquare = square(2);\nconsole.log(`The area of my square is ${mySquare.area()}`);\n
\nThe square
module is defined in square.js
:
// assigning to exports will not modify module, must use module.exports\nmodule.exports = (width) => {\n return {\n area: () => width * width\n };\n}\n
\nThe module system is implemented in the require("module")
module.
When a file is run directly from Node.js, require.main
is set to its\nmodule
. That means that you can determine whether a file has been run\ndirectly by testing
require.main === module\n
\nFor a file foo.js
, this will be true
if run via node foo.js
, but\nfalse
if run by require('./foo')
.
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
.
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.
Below we give a suggested directory structure that could work:
\nLet's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version>
hold the contents of a\nspecific version of a package.
Packages can depend on one another. In order to install package foo
, 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.
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:
/usr/lib/node/foo/1.2.3/
- Contents of the foo
package, version 1.2.3./usr/lib/node/bar/4.3.2/
- Contents of the bar
package that foo
\ndepends on./usr/lib/node/foo/1.2.3/node_modules/bar
- Symbolic link to\n/usr/lib/node/bar/4.3.2/
./usr/lib/node/bar/4.3.2/node_modules/*
- Symbolic links to the packages\nthat bar
depends on.Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.
\nWhen the code in the foo
package does require('bar')
, it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar
.\nThen, when the code in the bar
package calls require('quux')
, it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux
.
Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node
, we could put them in\n/usr/lib/node_modules/<name>/<version>
. Then Node.js will not bother\nlooking for missing dependencies in /usr/node_modules
or /node_modules
.
In order to make modules available to the Node.js REPL, it might be useful to\nalso add the /usr/lib/node_modules
folder to the $NODE_PATH
environment\nvariable. Since the module lookups using node_modules
folders are all\nrelative, and based on the real path of the files making the calls to\nrequire()
, the packages themselves can be anywhere.
To get the exact filename that will be loaded when require()
is called, use\nthe require.resolve()
function.
Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:
\nrequire(X) from module at path Y\n1. If X is a core module,\n a. return the core module\n b. STOP\n2. If X begins with './' 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 b. DIR = path join(PARTS[0 .. I] + "node_modules")\n c. DIRS = DIRS + DIR\n d. let I = I - 1\n5. return DIRS\n
\n"
},
{
"textRaw": "Caching",
"name": "Caching",
"type": "misc",
"desc": "Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo')
will get\nexactly the same object returned, if it would resolve to the same file.
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.
If you want to have a module execute code multiple times, then export a\nfunction, and call that function.
\n", "miscs": [ { "textRaw": "Module Caching Caveats", "name": "Module Caching Caveats", "type": "misc", "desc": "Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules
folders), it is not a guarantee\nthat require('foo')
will always return the exact same object, if it\nwould resolve to different files.
Additionally, on case-insensitive file systems or operating systems, different\nresolved filenames can point to the same file, but the cache will still treat\nthem as different modules and will reload the file multiple times. For example,\nrequire('./foo')
and require('./FOO')
return two different objects,\nirrespective of whether or not ./foo
and ./FOO
are the same file.
Node.js has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.
\nThe core modules are defined within Node.js's source and are located in the\nlib/
folder.
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.
When there are circular require()
calls, a module might not have finished\nexecuting when it is returned.
Consider this situation:
\na.js
:
console.log('a starting');\nexports.done = false;\nconst b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');\n
\nb.js
:
console.log('b starting');\nexports.done = false;\nconst a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');\n
\nmain.js
:
console.log('main starting');\nconst a = require('./a.js');\nconst b = require('./b.js');\nconsole.log('in main, a.done=%j, b.done=%j', a.done, b.done);\n
\nWhen main.js
loads a.js
, then a.js
in turn loads b.js
. At that\npoint, b.js
tries to load a.js
. In order to prevent an infinite\nloop, an unfinished copy of the a.js
exports object is returned to the\nb.js
module. b.js
then finishes loading, and its exports
object is\nprovided to the a.js
module.
By the time main.js
has loaded both modules, they're both finished.\nThe output of this program would thus be:
$ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done=true, b.done=true\n
\nIf you have cyclic module dependencies in your program, make sure to\nplan accordingly.
\n" }, { "textRaw": "File Modules", "name": "File Modules", "type": "misc", "desc": "If the exact filename is not found, then Node.js will attempt to load the\nrequired filename with the added extensions: .js
, .json
, and finally\n.node
.
.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
.
A required module prefixed with '/'
is an absolute path to the file. For\nexample, require('/home/marco/foo.js')
will load the file at\n/home/marco/foo.js
.
A required module prefixed with './'
is relative to the file calling\nrequire()
. That is, circle.js
must be in the same directory as foo.js
for\nrequire('./circle')
to find it.
Without a leading '/', './', or '../' to indicate a file, the module must\neither be a core module or is loaded from a node_modules
folder.
If the given path does not exist, require()
will throw an Error
with its\ncode
property set to 'MODULE_NOT_FOUND'
.
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.
The first is to create a package.json
file in the root of the folder,\nwhich specifies a main
module. An example package.json file might\nlook like this:
{ "name" : "some-library",\n "main" : "./lib/some-library.js" }\n
\nIf this was in a folder at ./some-library
, then\nrequire('./some-library')
would attempt to load\n./some-library/lib/some-library.js
.
This is the extent of Node.js's awareness of package.json files.
\nNote: 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:
Error: Cannot find module 'some-library'\n
\nIf 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:
./some-library/index.js
./some-library/index.node
If the module identifier passed to require()
is not a\ncore module, and does not begin with '/'
, '../'
, or\n'./'
, then Node.js starts at the parent directory of the current module, and\nadds /node_modules
, and attempts to load the module from that location. Node\nwill not append node_modules
to a path already ending in node_modules
.
If it is not found there, then it moves to the parent directory, and so\non, until the root of the file system is reached.
\nFor example, if the file at '/home/ry/projects/foo.js'
called\nrequire('bar.js')
, then Node.js would look in the following locations, in\nthis order:
/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js
This allows programs to localize their dependencies, so that they do not\nclash.
\nYou 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.
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.)
NODE_PATH
was originally created to support loading modules from\nvarying paths before the current module resolution algorithm was frozen.
NODE_PATH
is still supported, but is less necessary now that the Node.js\necosystem has settled on a convention for locating dependent modules.\nSometimes deployments that rely on NODE_PATH
show surprising behavior\nwhen people are unaware that NODE_PATH
must be set. Sometimes a\nmodule's dependencies change, causing a different version (or even a\ndifferent module) to be loaded as the NODE_PATH
is searched.
Additionally, Node.js will search in the following locations:
\n$HOME/.node_modules
$HOME/.node_libraries
$PREFIX/lib/node
Where $HOME
is the user's home directory, and $PREFIX
is Node.js's\nconfigured node_prefix
.
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.
Before a module's code is executed, Node.js will wrap it with a function\nwrapper that looks like the following:
\n(function (exports, require, module, __filename, __dirname) {\n// Your module code actually lives in here\n});\n
\nBy doing this, Node.js achieves a few things:
\nvar
, const
or let
) scoped to\nthe module rather than the global object.module
and exports
objects that the implementor can use to export\nvalues from the module.__filename
and __dirname
, containing the\nmodule's absolute filename and directory path.In each module, the module
free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports
is\nalso accessible via the exports
module-global. module
is not actually\na global but rather local to each module.
The module objects required by this one.
\n" }, { "textRaw": "`exports` {Object} ", "type": "Object", "name": "exports", "meta": { "added": [ "v0.1.16" ] }, "desc": "The module.exports
object is created by the Module system. Sometimes this is\nnot acceptable; many want their module to be an instance of some class. To do\nthis, assign the desired export object to module.exports
. Note that assigning\nthe desired object to exports
will simply rebind the local exports
variable,\nwhich is probably not what you want to do.
For example suppose we were making a module called a.js
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
\nThen in another file we could do
\nconst a = require('./a');\na.on('ready', () => {\n console.log('module a is ready');\n});\n
\nNote that assignment to module.exports
must be done immediately. It cannot be\ndone in any callbacks. This does not work:
x.js:
\nsetTimeout(() => {\n module.exports = { a: 'hello' };\n}, 0);\n
\ny.js:
\nconst x = require('./x');\nconsole.log(x.a);\n
\n",
"modules": [
{
"textRaw": "exports shortcut",
"name": "exports_shortcut",
"meta": {
"added": [
"v0.1.16"
]
},
"desc": "The exports
variable is available within a module's file-level scope, and is\nassigned the value of module.exports
before the module is evaluated.
It allows a shortcut, so that module.exports.f = ...
can be written more\nsuccinctly as exports.f = ...
. However, be aware that like any variable, if a\nnew value is assigned to exports
, it is no longer bound to module.exports
:
module.exports.hello = true; // Exported from require of module\nexports = { hello: false }; // Not exported, only available in the module\n
\nWhen the module.exports
property is being completely replaced by a new\nobject, it is common to also reassign exports
, for example:
module.exports = exports = function Constructor() {\n // ... etc.\n
\nTo illustrate the behavior, imagine this hypothetical implementation of\nrequire()
, which is quite similar to what is actually done by require()
:
function require(...) {\n var module = { exports: {} };\n ((module, exports) => {\n // Your module code here. In this example, define a function.\n function some_func() {};\n exports = some_func;\n // At this point, exports is no longer a shortcut to module.exports, and\n // this module will still export an empty default object.\n module.exports = some_func;\n // At this point, the module will now export some_func, instead of the\n // default object.\n })(module, module.exports);\n return module.exports;\n}\n
\n",
"type": "module",
"displayName": "exports shortcut"
}
]
},
{
"textRaw": "`filename` {String} ",
"type": "String",
"name": "filename",
"meta": {
"added": [
"v0.1.16"
]
},
"desc": "The fully resolved filename to the module.
\n" }, { "textRaw": "`id` {String} ", "type": "String", "name": "id", "meta": { "added": [ "v0.1.16" ] }, "desc": "The identifier for the module. Typically this is the fully resolved\nfilename.
\n" }, { "textRaw": "`loaded` {Boolean} ", "type": "Boolean", "name": "loaded", "meta": { "added": [ "v0.1.16" ] }, "desc": "Whether or not the module is done loading, or is in the process of\nloading.
\n" }, { "textRaw": "`parent` {Object} Module object ", "type": "Object", "name": "parent", "meta": { "added": [ "v0.1.16" ] }, "desc": "The module that first required this one.
\n", "shortDesc": "Module object" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "meta": { "added": [ "v0.5.1" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} `module.exports` from the resolved module ", "name": "return", "type": "Object", "desc": "`module.exports` from the resolved module" }, "params": [ { "textRaw": "`id` {String} ", "name": "id", "type": "String" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "The module.require
method provides a way to load a module as if\nrequire()
was called from the original module.
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.
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');
.
This class is used to create a TCP or local server.
\nnet.Server
is an EventEmitter
with the following events:
Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.
\n", "params": [] }, { "textRaw": "Event: 'connection'", "type": "event", "name": "connection", "meta": { "added": [ "v0.1.90" ] }, "params": [], "desc": "Emitted when a new connection is made. socket
is an instance of\nnet.Socket
.
Emitted when an error occurs. The 'close'
event will be called directly\nfollowing this event. See example in discussion of server.listen
.
Emitted when the server has been bound after calling server.listen
.
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 getting an OS-assigned address.\nReturns an object with port
, family
, and address
properties:\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }
Example:
\nvar server = net.createServer((socket) => {\n socket.end('goodbye\\n');\n}).on('error', (err) => {\n // handle errors here\n throw err;\n});\n\n// grab a random port.\nserver.listen(() => {\n console.log('opened server on', server.address());\n});\n
\nDon't call server.address()
until the 'listening'
event has been emitted.
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.
Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.
\nCallback should take two arguments err
and count
.
The handle
object can be set to either a server or socket (anything\nwith an underlying _handle
member), or a {fd: <n>}
object.
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.
\nListening on a file descriptor is not supported on Windows.
\nThis 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.
The parameter backlog
behaves the same as in\nserver.listen([port][, hostname][, backlog][, callback])
.
The port
, host
, and backlog
properties of options
, as well as the\noptional callback function, behave as they do on a call to\nserver.listen([port][, hostname][, backlog][, callback])
.\nAlternatively, the path
option can be used to specify a UNIX socket.
If exclusive
is false
(default), then cluster workers will use the same\nunderlying handle, allowing connection handling duties to be shared. When\nexclusive
is true
, the handle is not shared, and attempted port sharing\nresults in an error. An example which listens on an exclusive port is\nshown below.
server.listen({\n host: 'localhost',\n port: 80,\n exclusive: true\n});\n
\nNote: The server.listen()
method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.
Start a local socket server listening for connections on the given path
.
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.
On UNIX, the local domain is usually known as the UNIX domain. The path is a\nfilesystem path name. It gets truncated to sizeof(sockaddr_un.sun_path)
\nbytes, decreased by 1. It varies on different operating system between 91 and\n107 bytes. The typical values are 107 on Linux and 103 on OS X. The path is\nsubject to the same naming conventions and permissions checks as would be done\non file creation, will be visible in the filesystem, and will persist until\nunlinked.
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:
net.createServer().listen(\n path.join('\\\\\\\\?\\\\pipe', process.cwd(), 'myctl'))\n
\nThe parameter backlog
behaves the same as in\nserver.listen([port][, hostname][, backlog][, callback])
.
Note: The server.listen()
method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.
Begin accepting connections on the specified port
and hostname
. If the\nhostname
is omitted, the server will accept connections on any IPv6 address\n(::
) when IPv6 is available, or any IPv4 address (0.0.0.0
) otherwise.\nOmit the port argument, or use a port value of 0
, to have the operating system\nassign a random port, which can be retrieved by using server.address().port
\nafter the 'listening'
event has been emitted.
Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by the OS through sysctl settings such as\ntcp_max_syn_backlog
and somaxconn
on Linux. The default value of this\nparameter is 511 (not 512).
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.
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:
server.on('error', (e) => {\n if (e.code == 'EADDRINUSE') {\n console.log('Address in use, retrying...');\n setTimeout(() => {\n server.close();\n server.listen(PORT, HOST);\n }, 1000);\n }\n});\n
\n(Note: All sockets in Node.js are set SO_REUSEADDR
.)
Note: The server.listen()
method may be called multiple times. Each\nsubsequent call will re-open the server using the provided options.
Opposite of unref
, calling ref
on a previously unref
d server will not\nlet the program exit if it's the only server left (the default behavior). If\nthe server is ref
d calling ref
again will have no effect.
Returns server
.
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 unref
d calling\nunref
again will have no effect.
Returns server
.
The number of concurrent connections on the server.
\nThis becomes null
when sending a socket to a child with\nchild_process.fork()
. To poll forks and get current number of active\nconnections use asynchronous server.getConnections
instead.
A Boolean indicating whether or not the server is listening for\nconnections.
\n" }, { "textRaw": "server.maxConnections", "name": "maxConnections", "meta": { "added": [ "v0.2.0" ] }, "desc": "Set this property to reject connections when the server's connection count gets\nhigh.
\nIt is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork()
.
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.
Construct a new socket object.
\noptions
is an object with the following defaults:
{\n fd: null,\n allowHalfOpen: false,\n readable: false,\n writable: false\n}\n
\nfd
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.
net.Socket
instances are EventEmitter
with the following events:
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' }
Opens the connection for a given socket.
\nFor TCP sockets, options
argument should be an object which specifies:
port
: Port the client should connect to (Required).
host
: Host the client should connect to. Defaults to 'localhost'
.
localAddress
: Local interface to bind to for network connections.
localPort
: Local port to bind to for network connections.
family
: Version of IP stack. Defaults to 4
.
hints
: dns.lookup()
hints. Defaults to 0
.
lookup
: Custom lookup function. Defaults to dns.lookup
.
For local domain sockets, options
argument should be an object which\nspecifies:
path
: Path the client should connect to (Required).Normally this method is not needed, as net.createConnection
opens the\nsocket. Use this only if you are implementing a custom Socket.
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.
The connectListener
parameter will be added as a listener for the\n'connect'
event.
As socket.connect(options[, connectListener])
,\nwith options as either {port: port, host: host}
or {path: path}
.
As socket.connect(options[, connectListener])
,\nwith options as either {port: port, host: host}
or {path: path}
.
Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).
\nIf exception
is specified, an 'error'
event will be emitted and any\nlisteners for that event will receive exception
as an argument.
Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.
\nIf data
is specified, it is equivalent to calling\nsocket.write(data, encoding)
followed by socket.end()
.
Pauses the reading of data. That is, 'data'
events will not be emitted.\nUseful to throttle back an upload.
Opposite of unref
, calling ref
on a previously unref
d socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is ref
d calling ref
again will have no effect.
Returns socket
.
Resumes reading after a call to pause()
.
Set the encoding for the socket as a Readable Stream. See\nstream.setEncoding()
for more information.
Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.\nenable
defaults to false
.
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
.
Returns socket
.
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
.
Returns socket
.
Sets the socket to timeout after timeout
milliseconds of inactivity on\nthe socket. By default net.Socket
do not have a timeout.
When an idle timeout is triggered the socket will receive a 'timeout'
\nevent but the connection will not be severed. The user must manually end()
\nor destroy()
the socket.
If timeout
is 0, then the existing idle timeout is disabled.
The optional callback
parameter will be added as a one time listener for the\n'timeout'
event.
Returns socket
.
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 unref
d calling\nunref
again will have no effect.
Returns socket
.
Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.
\nReturns true
if the entire data was flushed successfully to the kernel\nbuffer. Returns false
if all or part of the data was queued in user memory.\n'drain'
will be emitted when the buffer is again free.
The optional callback
parameter will be executed when the data is finally\nwritten out - this may not be immediately.
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.
Emitted when a socket connection is successfully established.\nSee connect()
.
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.)
Note that the data will be lost if there is no listener when a Socket
\nemits a 'data'
event.
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
\nSee also: the return values of socket.write()
Emitted when the other end of the socket sends a FIN packet.
\nBy 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.
Emitted when an error occurs. The 'close'
event will be called directly\nfollowing this event.
Emitted after resolving the hostname but before connecting.\nNot applicable to UNIX sockets.
\nerr
{Error|Null} The error object. See dns.lookup()
.address
{String} The IP address.family
{String|Null} The address type. See dns.lookup()
.host
{String} The hostname.Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.
\nSee also: socket.setTimeout()
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).
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.)
\nUsers who experience large or growing bufferSize
should attempt to\n"throttle" the data flows in their program with pause()
and resume()
.
The amount of received bytes.
\n" }, { "textRaw": "socket.bytesWritten", "name": "bytesWritten", "meta": { "added": [ "v0.5.3" ] }, "desc": "The amount of bytes sent.
\n" }, { "textRaw": "socket.connecting", "name": "connecting", "meta": { "added": [ "v6.1.0" ] }, "desc": "If true
- socket.connect(options[, connectListener])
was called and\nhaven't yet finished. Will be set to false
before emitting connect
event\nand/or calling socket.connect(options[, connectListener])
's callback.
A Boolean value that indicates if the connection is destroyed or not. Once a\nconnection is destroyed no further data can be transferred using it.
\n" }, { "textRaw": "socket.localAddress", "name": "localAddress", "meta": { "added": [ "v0.9.6" ] }, "desc": "The string representation of the local IP address the remote client is\nconnecting on. For example, if you are listening on '0.0.0.0'
and the\nclient connects on '192.168.1.1'
, the value would be '192.168.1.1'
.
The numeric representation of the local port. For example,\n80
or 21
.
The string representation of the remote IP address. For example,\n'74.125.127.100'
or '2001:4860:a005::68'
. Value may be undefined
if\nthe socket is destroyed (for example, if the client disconnected).
The string representation of the remote IP family. 'IPv4'
or 'IPv6'
.
The numeric representation of the remote port. For example,\n80
or 21
.
A factory function, which returns a new net.Socket
and automatically\nconnects with the supplied options
.
The options are passed to both the net.Socket
constructor and the\nsocket.connect
method.
The connectListener
parameter will be added as a listener for the\n'connect'
event once.
Here is an example of a client of the previously described echo server:
\nconst 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
\nTo connect on the socket /tmp/echo.sock
the second line would just be\nchanged to
const client = net.connect({path: '/tmp/echo.sock'});\n
\n",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "connectListener",
"optional": true
}
]
}
]
},
{
"textRaw": "net.connect(path[, connectListener])",
"type": "method",
"name": "connect",
"meta": {
"added": [
"v0.1.90"
]
},
"desc": "A factory function, which returns a new unix net.Socket
and automatically\nconnects to the supplied path
.
The connectListener
parameter will be added as a listener for the\n'connect'
event once.
A factory function, which returns a new net.Socket
and automatically\nconnects to the supplied port
and host
.
If host
is omitted, 'localhost'
will be assumed.
The connectListener
parameter will be added as a listener for the\n'connect'
event once.
A factory function, which returns a new net.Socket
and automatically\nconnects with the supplied options
.
The options are passed to both the net.Socket
constructor and the\nsocket.connect
method.
Passing timeout
as an option will call socket.setTimeout()
after the socket is created, but before it is connecting.
The connectListener
parameter will be added as a listener for the\n'connect'
event once.
Here is an example of a client of the previously described echo server:
\nconst 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
\nTo connect on the socket /tmp/echo.sock
the second line would just be\nchanged to
const client = net.connect({path: '/tmp/echo.sock'});\n
\n",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "connectListener",
"optional": true
}
]
}
]
},
{
"textRaw": "net.createConnection(path[, connectListener])",
"type": "method",
"name": "createConnection",
"meta": {
"added": [
"v0.1.90"
]
},
"desc": "A factory function, which returns a new unix net.Socket
and automatically\nconnects to the supplied path
.
The connectListener
parameter will be added as a listener for the\n'connect'
event once.
A factory function, which returns a new net.Socket
and automatically\nconnects to the supplied port
and host
.
If host
is omitted, 'localhost'
will be assumed.
The connectListener
parameter will be added as a listener for the\n'connect'
event once.
Creates a new server. The connectionListener
argument is\nautomatically set as a listener for the 'connection'
event.
options
is an object with the following defaults:
{\n allowHalfOpen: false,\n pauseOnConnect: false\n}\n
\nIf 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.
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()
.
Here is an example of an echo server which listens for connections\non port 8124:
\nconst 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
\nTest this by using telnet
:
telnet localhost 8124\n
\nTo listen on the socket /tmp/echo.sock
the third line from the last would\njust be changed to
server.listen('/tmp/echo.sock', () => {\n console.log('server bound');\n});\n
\nUse nc
to connect to a UNIX domain socket server:
nc -U /tmp/echo.sock\n
\n",
"signatures": [
{
"params": [
{
"name": "options",
"optional": true
},
{
"name": "connectionListener",
"optional": true
}
]
}
]
},
{
"textRaw": "net.isIP(input)",
"type": "method",
"name": "isIP",
"meta": {
"added": [
"v0.3.0"
]
},
"desc": "Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.
\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv4(input)", "type": "method", "name": "isIPv4", "meta": { "added": [ "v0.3.0" ] }, "desc": "Returns true if input is a version 4 IP address, otherwise returns false.
\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv6(input)", "type": "method", "name": "isIPv6", "meta": { "added": [ "v0.3.0" ] }, "desc": "Returns true if input is a version 6 IP address, otherwise returns false.
\n\n\n", "signatures": [ { "params": [ { "name": "input" } ] } ] } ], "type": "module", "displayName": "net" }, { "textRaw": "OS", "name": "os", "stability": 2, "stabilityText": "Stable", "desc": "The os
module provides a number of operating system-related utility methods.\nIt can be accessed using:
const os = require('os');\n
\n",
"properties": [
{
"textRaw": "`EOL` {String} ",
"type": "String",
"name": "EOL",
"meta": {
"added": [
"v0.7.8"
]
},
"desc": "A string constant defining the operating system-specific end-of-line marker:
\n\\n
on POSIX\\r\\n
on WindowsReturns an object containing commonly used operating system specific constants\nfor error codes, process signals, and so on. The specific constants currently\ndefined are described in OS Constants.
\n" } ], "methods": [ { "textRaw": "os.arch()", "type": "method", "name": "arch", "meta": { "added": [ "v0.5.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {String} ", "name": "return", "type": "String" }, "params": [] }, { "params": [] } ], "desc": "The os.arch()
method returns a string identifying the operating system CPU\narchitecture for which the Node.js binary was compiled.
The current possible values are: 'arm'
, 'arm64'
, 'ia32'
, 'mips'
,\n'mipsel'
, 'ppc'
, 'ppc64'
, 's390'
, 's390x'
, 'x32'
, 'x64'
, and\n'x86'
.
Equivalent to process.arch
.
The os.cpus()
method returns an array of objects containing information about\neach CPU/core installed.
The properties included on each object include:
\nmodel
{String}speed
{number} (in MHz)times
{Object}user
{number} The number of milliseconds the CPU has spent in user mode.nice
{number} The number of milliseconds the CPU has spent in nice mode.sys
{number} The number of milliseconds the CPU has spent in sys mode.idle
{number} The number of milliseconds the CPU has spent in idle mode.irq
{number} The number of milliseconds the CPU has spent in irq mode.For example:
\n[\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 252020,\n nice: 0,\n sys: 30340,\n idle: 1070356870,\n irq: 0\n }\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 306960,\n nice: 0,\n sys: 26980,\n idle: 1071569080,\n irq: 0\n }\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 248450,\n nice: 0,\n sys: 21750,\n idle: 1070919370,\n irq: 0\n }\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 256880,\n nice: 0,\n sys: 19430,\n idle: 1070905480,\n irq: 20\n }\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 511580,\n nice: 20,\n sys: 40900,\n idle: 1070842510,\n irq: 0\n }\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 291660,\n nice: 0,\n sys: 34360,\n idle: 1070888000,\n irq: 10\n }\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 308260,\n nice: 0,\n sys: 55410,\n idle: 1071129970,\n irq: 880\n }\n },\n {\n model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',\n speed: 2926,\n times: {\n user: 266450,\n nice: 1480,\n sys: 34920,\n idle: 1072572010,\n irq: 30\n }\n }\n]\n
\nNote: Because nice
values are UNIX-specific, on Windows the nice
values of\nall processors are always 0.
The os.endianness()
method returns a string identifying the endianness of the\nCPU for which the Node.js binary was compiled.
Possible values are:
\n'BE'
for big endian'LE'
for little endian.The os.freemem()
method returns the amount of free system memory in bytes as\nan integer.
The os.homedir()
method returns the home directory of the current user as a\nstring.
The os.hostname()
method returns the hostname of the operating system as a\nstring.
The os.loadavg()
method returns an array containing the 1, 5, and 15 minute\nload averages.
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.
\nThe load average is a UNIX-specific concept with no real equivalent on\nWindows platforms. On Windows, the return value is always [0, 0, 0]
.
The os.networkInterfaces()
method returns an object containing only network\ninterfaces that have been assigned a network address.
Each key on the returned object identifies a network interface. The associated\nvalue is an array of objects that each describe an assigned network address.
\nThe properties available on the assigned network address object include:
\naddress
{String} The assigned IPv4 or IPv6 addressnetmask
{String} The IPv4 or IPv6 network maskfamily
{String} Either IPv4
or IPv6
mac
{String} The MAC address of the network interfaceinternal
{boolean} true
if the network interface is a loopback or\nsimilar interface that is not remotely accessible; otherwise false
scopeid
{number} The numeric IPv6 scope ID (only specified when family
\nis IPv6
){\n lo: [\n {\n address: '127.0.0.1',\n netmask: '255.0.0.0',\n family: 'IPv4',\n mac: '00:00:00:00:00:00',\n internal: true\n },\n {\n address: '::1',\n netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',\n family: 'IPv6',\n mac: '00:00:00:00:00:00',\n internal: true\n }\n ],\n eth0: [\n {\n address: '192.168.1.108',\n netmask: '255.255.255.0',\n family: 'IPv4',\n mac: '01:02:03:0a:0b:0c',\n internal: false\n },\n {\n address: 'fe80::a00:27ff:fe4e:66a1',\n netmask: 'ffff:ffff:ffff:ffff::',\n family: 'IPv6',\n mac: '01:02:03:0a:0b:0c',\n internal: false\n }\n ]\n}\n
\n"
},
{
"textRaw": "os.platform()",
"type": "method",
"name": "platform",
"meta": {
"added": [
"v0.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {String} ",
"name": "return",
"type": "String"
},
"params": []
},
{
"params": []
}
],
"desc": "The os.platform()
method returns a string identifying the operating system\nplatform as set during compile time of Node.js.
Currently possible values are:
\n'aix'
'darwin'
'freebsd'
'linux'
'openbsd'
'sunos'
'win32'
Equivalent to process.platform
.
Note: The value 'android'
may also be returned if the Node.js is built on\nthe Android operating system. However, Android support in Node.js is considered\nto be experimental at this time.
The os.release()
method returns a string identifying the operating system\nrelease.
Note: On POSIX systems, the operating system release is determined by calling\nuname(3). On Windows, GetVersionExW()
is used. Please see\nhttps://en.wikipedia.org/wiki/Uname#Examples for more information.
The os.tmpdir()
method returns a string specifying the operating system's\ndefault directory for temporary files.
The os.totalmem()
method returns the total amount of system memory in bytes\nas an integer.
The os.type()
method returns a string identifying the operating system name\nas returned by uname(3). For example 'Linux'
on Linux, 'Darwin'
on OS X and\n'Windows_NT'
on Windows.
Please see https://en.wikipedia.org/wiki/Uname#Examples for additional\ninformation about the output of running uname(3) on various operating systems.
\n" }, { "textRaw": "os.uptime()", "type": "method", "name": "uptime", "meta": { "added": [ "v0.3.3" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Integer} ", "name": "return", "type": "Integer" }, "params": [] }, { "params": [] } ], "desc": "The os.uptime()
method returns the system uptime in number of seconds.
Note: Within Node.js' internals, this number is represented as a double
.\nHowever, fractional seconds are not returned and the value can typically be\ntreated as an integer.
The os.userInfo()
method returns information about the currently effective\nuser -- on POSIX platforms, this is typically a subset of the password file. The\nreturned object includes the username
, uid
, gid
, shell
, and homedir
.\nOn Windows, the uid
and gid
fields are -1
, and shell
is null
.
The value of homedir
returned by os.userInfo()
is provided by the operating\nsystem. This differs from the result of os.homedir()
, which queries several\nenvironment variables for the home directory before falling back to the\noperating system response.
The following constants are exported by os.constants
. Note: Not all\nconstants will be available on every operating system.
The following signal constants are exported by os.constants.signals
:
Constant | \nDescription | \n
---|---|
SIGHUP | \n Sent to indicate when a controlling terminal is closed or a parent\n process exits. | \n
SIGINT | \n Sent to indicate when a user wishes to interrupt a process\n ((Ctrl+C) ). | \n
SIGQUIT | \n Sent to indicate when a user wishes to terminate a process and perform a\n core dump. | \n
SIGILL | \n Sent to a process to notify that it has attempted to perform an illegal,\n malformed, unknown or privileged instruction. | \n
SIGTRAP | \n Sent to a process when an exception has occurred. | \n
SIGABRT | \n Sent to a process to request that it abort. | \n
SIGIOT | \n Synonym for SIGABRT | \n
SIGBUS | \n Sent to a process to notify that it has caused a bus error. | \n
SIGFPE | \n Sent to a process to notify that it has performed an illegal arithmetic\n operation. | \n
SIGKILL | \n Sent to a process to terminate it immediately. | \n
SIGUSR1 SIGUSR2 | \n Sent to a process to identify user-defined conditions. | \n
SIGSEGV | \n Sent to a process to notify of a segmentation fault. | \n
SIGPIPE | \n Sent to a process when it has attempted to write to a disconnected\n pipe. | \n
SIGALRM | \n Sent to a process when a system timer elapses. | \n
SIGTERM | \n Sent to a process to request termination. | \n
SIGCHLD | \n Sent to a process when a child process terminates. | \n
SIGSTKFLT | \n Sent to a process to indicate a stack fault on a coprocessor. | \n
SIGCONT | \n Sent to instruct the operating system to continue a paused process. | \n
SIGSTOP | \n Sent to instruct the operating system to halt a process. | \n
SIGTSTP | \n Sent to a process to request it to stop. | \n
SIGBREAK | \n Sent to indicate when a user wishes to interrupt a process. | \n
SIGTTIN | \n Sent to a process when it reads from the TTY while in the\n background. | \n
SIGTTOU | \n Sent to a process when it writes to the TTY while in the\n background. | \n
SIGURG | \n Sent to a process when a socket has urgent data to read. | \n
SIGXCPU | \n Sent to a process when it has exceeded its limit on CPU usage. | \n
SIGXFSZ | \n Sent to a process when it grows a file larger than the maximum\n allowed. | \n
SIGVTALRM | \n Sent to a process when a virtual timer has elapsed. | \n
SIGPROF | \n Sent to a process when a system timer has elapsed. | \n
SIGWINCH | \n Sent to a process when the controlling terminal has changed its\n size. | \n
SIGIO | \n Sent to a process when I/O is available. | \n
SIGPOLL | \n Synonym for SIGIO | \n
SIGLOST | \n Sent to a process when a file lock has been lost. | \n
SIGPWR | \n Sent to a process to notify of a power failure. | \n
SIGINFO | \n Synonym for SIGPWR | \n
SIGSYS | \n Sent to a process to notify of a bad argument. | \n
SIGUNUSED | \n Synonym for SIGSYS | \n
The following error constants are exported by os.constants.errno
:
Constant | \nDescription | \n
---|---|
E2BIG | \n Indicates that the list of arguments is longer than expected. | \n
EACCES | \n Indicates that the operation did not have sufficient permissions. | \n
EADDRINUSE | \n Indicates that the network address is already in use. | \n
EADDRNOTAVAIL | \n Indicates that the network address is currently unavailable for\n use. | \n
EAFNOSUPPORT | \n Indicates that the network address family is not supported. | \n
EAGAIN | \n Indicates that there is currently no data available and to try the\n operation again later. | \n
EALREADY | \n Indicates that the socket already has a pending connection in\n progress. | \n
EBADF | \n Indicates that a file descriptor is not valid. | \n
EBADMSG | \n Indicates an invalid data message. | \n
EBUSY | \n Indicates that a device or resource is busy. | \n
ECANCELED | \n Indicates that an operation was canceled. | \n
ECHILD | \n Indicates that there are no child processes. | \n
ECONNABORTED | \n Indicates that the network connection has been aborted. | \n
ECONNREFUSED | \n Indicates that the network connection has been refused. | \n
ECONNRESET | \n Indicates that the network connection has been reset. | \n
EDEADLK | \n Indicates that a resource deadlock has been avoided. | \n
EDESTADDRREQ | \n Indicates that a destination address is required. | \n
EDOM | \n Indicates that an argument is out of the domain of the function. | \n
EDQUOT | \n Indicates that the disk quota has been exceeded. | \n
EEXIST | \n Indicates that the file already exists. | \n
EFAULT | \n Indicates an invalid pointer address. | \n
EFBIG | \n Indicates that the file is too large. | \n
EHOSTUNREACH | \n Indicates that the host is unreachable. | \n
EIDRM | \n Indicates that the identifier has been removed. | \n
EILSEQ | \n Indicates an illegal byte sequence. | \n
EINPROGRESS | \n Indicates that an operation is already in progress. | \n
EINTR | \n Indicates that a function call was interrupted. | \n
EINVAL | \n Indicates that an invalid argument was provided. | \n
EIO | \n Indicates an otherwise unspecified I/O error. | \n
EISCONN | \n Indicates that the socket is connected. | \n
EISDIR | \n Indicates that the path is a directory. | \n
ELOOP | \n Indicates too many levels of symbolic links in a path. | \n
EMFILE | \n Indicates that there are too many open files. | \n
EMLINK | \n Indicates that there are too many hard links to a file. | \n
EMSGSIZE | \n Indicates that the provided message is too long. | \n
EMULTIHOP | \n Indicates that a multihop was attempted. | \n
ENAMETOOLONG | \n Indicates that the filename is too long. | \n
ENETDOWN | \n Indicates that the network is down. | \n
ENETRESET | \n Indicates that the connection has been aborted by the network. | \n
ENETUNREACH | \n Indicates that the network is unreachable. | \n
ENFILE | \n Indicates too many open files in the system. | \n
ENOBUFS | \n Indicates that no buffer space is available. | \n
ENODATA | \n Indicates that no message is available on the stream head read\n queue. | \n
ENODEV | \n Indicates that there is no such device. | \n
ENOENT | \n Indicates that there is no such file or directory. | \n
ENOEXEC | \n Indicates an exec format error. | \n
ENOLCK | \n Indicates that there are no locks available. | \n
ENOLINK | \n Indications that a link has been severed. | \n
ENOMEM | \n Indicates that there is not enough space. | \n
ENOMSG | \n Indicates that there is no message of the desired type. | \n
ENOPROTOOPT | \n Indicates that a given protocol is not available. | \n
ENOSPC | \n Indicates that there is no space available on the device. | \n
ENOSR | \n Indicates that there are no stream resources available. | \n
ENOSTR | \n Indicates that a given resource is not a stream. | \n
ENOSYS | \n Indicates that a function has not been implemented. | \n
ENOTCONN | \n Indicates that the socket is not connected. | \n
ENOTDIR | \n Indicates that the path is not a directory. | \n
ENOTEMPTY | \n Indicates that the directory is not empty. | \n
ENOTSOCK | \n Indicates that the given item is not a socket. | \n
ENOTSUP | \n Indicates that a given operation is not supported. | \n
ENOTTY | \n Indicates an inappropriate I/O control operation. | \n
ENXIO | \n Indicates no such device or address. | \n
EOPNOTSUPP | \n Indicates that an operation is not supported on the socket.\n Note that while ENOTSUP and EOPNOTSUPP have the same value on Linux,\n according to POSIX.1 these error values should be distinct.) | \n
EOVERFLOW | \n Indicates that a value is too large to be stored in a given data\n type. | \n
EPERM | \n Indicates that the operation is not permitted. | \n
EPIPE | \n Indicates a broken pipe. | \n
EPROTO | \n Indicates a protocol error. | \n
EPROTONOSUPPORT | \n Indicates that a protocol is not supported. | \n
EPROTOTYPE | \n Indicates the wrong type of protocol for a socket. | \n
ERANGE | \n Indicates that the results are too large. | \n
EROFS | \n Indicates that the file system is read only. | \n
ESPIPE | \n Indicates an invalid seek operation. | \n
ESRCH | \n Indicates that there is no such process. | \n
ESTALE | \n Indicates that the file handle is stale. | \n
ETIME | \n Indicates an expired timer. | \n
ETIMEDOUT | \n Indicates that the connection timed out. | \n
ETXTBSY | \n Indicates that a text file is busy. | \n
EWOULDBLOCK | \n Indicates that the operation would block. | \n
EXDEV | \n Indicates an improper link.\n |
The following error codes are specific to the Windows operating system:
\nConstant | \nDescription | \n
---|---|
WSAEINTR | \n Indicates an interrupted function call. | \n
WSAEBADF | \n Indicates an invalid file handle. | \n
WSAEACCES | \n Indicates insufficient permissions to complete the operation. | \n
WSAEFAULT | \n Indicates an invalid pointer address. | \n
WSAEINVAL | \n Indicates that an invalid argument was passed. | \n
WSAEMFILE | \n Indicates that there are too many open files. | \n
WSAEWOULDBLOCK | \n Indicates that a resource is temporarily unavailable. | \n
WSAEINPROGRESS | \n Indicates that an operation is currently in progress. | \n
WSAEALREADY | \n Indicates that an operation is already in progress. | \n
WSAENOTSOCK | \n Indicates that the resource is not a socket. | \n
WSAEDESTADDRREQ | \n Indicates that a destination address is required. | \n
WSAEMSGSIZE | \n Indicates that the message size is too long. | \n
WSAEPROTOTYPE | \n Indicates the wrong protocol type for the socket. | \n
WSAENOPROTOOPT | \n Indicates a bad protocol option. | \n
WSAEPROTONOSUPPORT | \n Indicates that the protocol is not supported. | \n
WSAESOCKTNOSUPPORT | \n Indicates that the socket type is not supported. | \n
WSAEOPNOTSUPP | \n Indicates that the operation is not supported. | \n
WSAEPFNOSUPPORT | \n Indicates that the protocol family is not supported. | \n
WSAEAFNOSUPPORT | \n Indicates that the address family is not supported. | \n
WSAEADDRINUSE | \n Indicates that the network address is already in use. | \n
WSAEADDRNOTAVAIL | \n Indicates that the network address is not available. | \n
WSAENETDOWN | \n Indicates that the network is down. | \n
WSAENETUNREACH | \n Indicates that the network is unreachable. | \n
WSAENETRESET | \n Indicates that the network connection has been reset. | \n
WSAECONNABORTED | \n Indicates that the connection has been aborted. | \n
WSAECONNRESET | \n Indicates that the connection has been reset by the peer. | \n
WSAENOBUFS | \n Indicates that there is no buffer space available. | \n
WSAEISCONN | \n Indicates that the socket is already connected. | \n
WSAENOTCONN | \n Indicates that the socket is not connected. | \n
WSAESHUTDOWN | \n Indicates that data cannot be sent after the socket has been\n shutdown. | \n
WSAETOOMANYREFS | \n Indicates that there are too many references. | \n
WSAETIMEDOUT | \n Indicates that the connection has timed out. | \n
WSAECONNREFUSED | \n Indicates that the connection has been refused. | \n
WSAELOOP | \n Indicates that a name cannot be translated. | \n
WSAENAMETOOLONG | \n Indicates that a name was too long. | \n
WSAEHOSTDOWN | \n Indicates that a network host is down. | \n
WSAEHOSTUNREACH | \n Indicates that there is no route to a network host. | \n
WSAENOTEMPTY | \n Indicates that the directory is not empty. | \n
WSAEPROCLIM | \n Indicates that there are too many processes. | \n
WSAEUSERS | \n Indicates that the user quota has been exceeded. | \n
WSAEDQUOT | \n Indicates that the disk quota has been exceeded. | \n
WSAESTALE | \n Indicates a stale file handle reference. | \n
WSAEREMOTE | \n Indicates that the item is remote. | \n
WSASYSNOTREADY | \n Indicates that the network subsystem is not ready. | \n
WSAVERNOTSUPPORTED | \n Indicates that the winsock.dll version is out of range. | \n
WSANOTINITIALISED | \n Indicates that successful WSAStartup has not yet been performed. | \n
WSAEDISCON | \n Indicates that a graceful shutdown is in progress. | \n
WSAENOMORE | \n Indicates that there are no more results. | \n
WSAECANCELLED | \n Indicates that an operation has been canceled. | \n
WSAEINVALIDPROCTABLE | \n Indicates that the procedure call table is invalid. | \n
WSAEINVALIDPROVIDER | \n Indicates an invalid service provider. | \n
WSAEPROVIDERFAILEDINIT | \n Indicates that the service provider failed to initialized. | \n
WSASYSCALLFAILURE | \n Indicates a system call failure. | \n
WSASERVICE_NOT_FOUND | \n Indicates that a service was not found. | \n
WSATYPE_NOT_FOUND | \n Indicates that a class type was not found. | \n
WSA_E_NO_MORE | \n Indicates that there are no more results. | \n
WSA_E_CANCELLED | \n Indicates that the call was canceled. | \n
WSAEREFUSED | \n Indicates that a database query was refused. | \n
Constant | \nDescription | \n
---|---|
UV_UDP_REUSEADDR | \n \n |
The path
module provides utilities for working with file and directory paths.\nIt can be accessed using:
const path = require('path');\n
\n",
"modules": [
{
"textRaw": "Windows vs. POSIX",
"name": "windows_vs._posix",
"desc": "The default operation of the path
module varies based on the operating system\non which a Node.js application is running. Specifically, when running on a\nWindows operating system, the path
module will assume that Windows-style\npaths are being used.
For example, using the path.basename()
function with the Windows file path\nC:\\temp\\myfile.html
, will yield different results when running on POSIX than\nwhen run on Windows:
On POSIX:
\npath.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'C:\\\\temp\\\\myfile.html'\n
\nOn Windows:
\npath.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n
\nTo achieve consistent results when working with Windows file paths on any\noperating system, use path.win32
:
On POSIX and Windows:
\npath.win32.basename('C:\\\\temp\\\\myfile.html');\n// Returns: 'myfile.html'\n
\nTo achieve consistent results when working with POSIX file paths on any\noperating system, use path.posix
:
On POSIX and Windows:
\npath.posix.basename('/tmp/myfile.html');\n// Returns: 'myfile.html'\n
\n",
"type": "module",
"displayName": "Windows vs. POSIX"
}
],
"methods": [
{
"textRaw": "path.basename(path[, ext])",
"type": "method",
"name": "basename",
"meta": {
"added": [
"v0.1.25"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {String} ",
"name": "return",
"type": "String"
},
"params": [
{
"textRaw": "`path` {String} ",
"name": "path",
"type": "String"
},
{
"textRaw": "`ext` {String} An optional file extension ",
"name": "ext",
"type": "String",
"desc": "An optional file extension",
"optional": true
}
]
},
{
"params": [
{
"name": "path"
},
{
"name": "ext",
"optional": true
}
]
}
],
"desc": "The path.basename()
methods returns the last portion of a path
, similar to\nthe Unix basename
command.
For example:
\npath.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
\nA TypeError
is thrown if path
is not a string or if ext
is given\nand is not a string.
The path.dirname()
method returns the directory name of a path
, similar to\nthe Unix dirname
command.
For example:
\npath.dirname('/foo/bar/baz/asdf/quux')\n// Returns: '/foo/bar/baz/asdf'\n
\nA TypeError
is thrown if path
is not a string.
The path.extname()
method returns the extension of the path
, from the last\noccurrence of the .
(period) character to end of string in the last portion of\nthe path
. If there is no .
in the last portion of the path
, or if the\nfirst character of the basename of path
(see path.basename()
) is .
, then\nan empty string is returned.
For example:
\npath.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
\nA TypeError
is thrown if path
is not a string.
The path.format()
method returns a path string from an object. This is the\nopposite of path.parse()
.
When providing properties to the pathObject
remember that there are\ncombinations where one property has priority over another:
pathObject.root
is ignored if pathObject.dir
is providedpathObject.ext
and pathObject.name
are ignored if pathObject.base
existsFor example, on POSIX:
\n// If `dir`, `root` and `base` are provided,\n// `${dir}${path.sep}${base}`\n// will be returned. `root` is ignored.\npath.format({\n root: '/ignored',\n dir: '/home/user/dir',\n base: 'file.txt'\n});\n// Returns: '/home/user/dir/file.txt'\n\n// `root` will be used if `dir` is not specified.\n// If only `root` is provided or `dir` is equal to `root` then the\n// platform separator will not be included. `ext` will be ignored.\npath.format({\n root: '/',\n base: 'file.txt',\n ext: 'ignored'\n});\n// Returns: '/file.txt'\n\n// `name` + `ext` will be used if `base` is not specified.\npath.format({\n root: '/',\n name: 'file',\n ext: '.txt'\n});\n// Returns: '/file.txt'\n
\nOn Windows:
\npath.format({\n dir : "C:\\\\path\\\\dir",\n base : "file.txt"\n});\n// Returns: 'C:\\\\path\\\\dir\\\\file.txt'\n
\n"
},
{
"textRaw": "path.isAbsolute(path)",
"type": "method",
"name": "isAbsolute",
"meta": {
"added": [
"v0.11.2"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Boolean} ",
"name": "return",
"type": "Boolean"
},
"params": [
{
"textRaw": "`path` {String} ",
"name": "path",
"type": "String"
}
]
},
{
"params": [
{
"name": "path"
}
]
}
],
"desc": "The path.isAbsolute()
method determines if path
is an absolute path.
If the given path
is a zero-length string, false
will be returned.
For example on POSIX:
\npath.isAbsolute('/foo/bar') // true\npath.isAbsolute('/baz/..') // true\npath.isAbsolute('qux/') // false\npath.isAbsolute('.') // false\n
\nOn Windows:
\npath.isAbsolute('//server') // true\npath.isAbsolute('\\\\\\\\server') // true\npath.isAbsolute('C:/foo/..') // true\npath.isAbsolute('C:\\\\foo\\\\..') // true\npath.isAbsolute('bar\\\\baz') // false\npath.isAbsolute('bar/baz') // false\npath.isAbsolute('.') // false\n
\nA TypeError
is thrown if path
is not a string.
The path.join()
method joins all given path
segments together using the\nplatform specific separator as a delimiter, then normalizes the resulting path.
Zero-length path
segments are ignored. If the joined path string is a\nzero-length string then '.'
will be returned, representing the current\nworking directory.
For example:
\npath.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n// Returns: '/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar')\n// throws TypeError: Arguments to path.join must be strings\n
\nA TypeError
is thrown if any of the path segments is not a string.
The path.normalize()
method normalizes the given path
, resolving '..'
and\n'.'
segments.
When multiple, sequential path segment separation characters are found (e.g.\n/
on POSIX and \\
on Windows), they are replaced by a single instance of the\nplatform specific path segment separator. Trailing separators are preserved.
If the path
is a zero-length string, '.'
is returned, representing the\ncurrent working directory.
For example on POSIX:
\npath.normalize('/foo/bar//baz/asdf/quux/..')\n// Returns: '/foo/bar/baz/asdf'\n
\nOn Windows:
\npath.normalize('C:\\\\temp\\\\\\\\foo\\\\bar\\\\..\\\\');\n// Returns: 'C:\\\\temp\\\\foo\\\\'\n
\nA TypeError
is thrown if path
is not a string.
The path.parse()
method returns an object whose properties represent\nsignificant elements of the path
.
The returned object will have the following properties:
\nroot
{String}dir
{String}base
{String}ext
{String}name
{String}For example on POSIX:
\npath.parse('/home/user/dir/file.txt')\n// Returns:\n// {\n// root : "/",\n// dir : "/home/user/dir",\n// base : "file.txt",\n// ext : ".txt",\n// name : "file"\n// }\n
\n┌─────────────────────┬────────────┐\n│ dir │ base │\n├──────┬ ├──────┬─────┤\n│ root │ │ name │ ext │\n" / home/user/dir / file .txt "\n└──────┴──────────────┴──────┴─────┘\n(all spaces in the "" line should be ignored -- they are purely for formatting)\n
\nOn Windows:
\npath.parse('C:\\\\path\\\\dir\\\\file.txt')\n// Returns:\n// {\n// root : "C:\\\\",\n// dir : "C:\\\\path\\\\dir",\n// base : "file.txt",\n// ext : ".txt",\n// name : "file"\n// }\n
\n┌─────────────────────┬────────────┐\n│ dir │ base │\n├──────┬ ├──────┬─────┤\n│ root │ │ name │ ext │\n" C:\\ path\\dir \\ file .txt "\n└──────┴──────────────┴──────┴─────┘\n(all spaces in the "" line should be ignored -- they are purely for formatting)\n
\nA TypeError
is thrown if path
is not a string.
The path.relative()
method returns the relative path from from
to to
.\nIf from
and to
each resolve to the same path (after calling path.resolve()
\non each), a zero-length string is returned.
If a zero-length string is passed as from
or to
, the current working\ndirectory will be used instead of the zero-length strings.
For example on POSIX:
\npath.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n// Returns: '../../impl/bbb'\n
\nOn Windows:
\npath.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n// Returns: '..\\\\..\\\\impl\\\\bbb'\n
\nA TypeError
is thrown if neither from
nor to
is a string.
The path.resolve()
method resolves a sequence of paths or path segments into\nan absolute path.
The given sequence of paths is processed from right to left, with each\nsubsequent path
prepended until an absolute path is constructed.\nFor instance, given the sequence of path segments: /foo
, /bar
, baz
,\ncalling path.resolve('/foo', '/bar', 'baz')
would return /bar/baz
.
If after processing all given path
segments an absolute path has not yet\nbeen generated, the current working directory is used.
The resulting path is normalized and trailing slashes are removed unless the\npath is resolved to the root directory.
\nZero-length path
segments are ignored.
If no path
segments are passed, path.resolve()
will return the absolute path\nof the current working directory.
For example:
\npath.resolve('/foo/bar', './baz')\n// Returns: '/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/')\n// Returns: '/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')\n// if the current working directory is /home/myself/node,\n// this returns '/home/myself/node/wwwroot/static_files/gif/image.gif'\n
\nA TypeError
is thrown if any of the arguments is not a string.
Provides the platform-specific path delimiter:
\n;
for Windows:
for POSIXFor example, on POSIX:
\nconsole.log(process.env.PATH)\n// Prints: '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'\n\nprocess.env.PATH.split(path.delimiter)\n// Returns: ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']\n
\nOn Windows:
\nconsole.log(process.env.PATH)\n// Prints: 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\node\\'\n\nprocess.env.PATH.split(path.delimiter)\n// Returns: ['C:\\\\Windows\\\\system32', 'C:\\\\Windows', 'C:\\\\Program Files\\\\node\\\\']\n
\n"
},
{
"textRaw": "`posix` {Object} ",
"type": "Object",
"name": "posix",
"meta": {
"added": [
"v0.11.15"
]
},
"desc": "The path.posix
property provides access to POSIX specific implementations\nof the path
methods.
Provides the platform-specific path segment separator:
\n\\
on Windows/
on POSIXFor example on POSIX:
\n'foo/bar/baz'.split(path.sep)\n// Returns: ['foo', 'bar', 'baz']\n
\nOn Windows:
\n'foo\\\\bar\\\\baz'.split(path.sep)\n// Returns: ['foo', 'bar', 'baz']\n
\n"
},
{
"textRaw": "`win32` {Object} ",
"type": "Object",
"name": "win32",
"meta": {
"added": [
"v0.11.15"
]
},
"desc": "The path.win32
property provides access to Windows-specific implementations\nof the path
methods.
Note: On Windows, both the forward slash (/
) and backward slash (\\
)\ncharacters are accepted as path delimiters; however, only the backward slash\n(\\
) will be used in return values.
The version of the punycode module bundled in Node.js is being deprecated.\nIn a future major version of Node.js this module will be removed. Users\ncurrently depending on the punycode
module should switch to using the\nuserland-provided Punycode.js module instead.
The punycode
module is a bundled version of the Punycode.js module. It\ncan be accessed using:
const punycode = require('punycode');\n
\nPunycode is a character encoding scheme defined by RFC 3492 that is\nprimarily intended for use in Internationalized Domain Names. Because host\nnames in URLs are limited to ASCII characters only, Domain Names that contain\nnon-ASCII characters must be converted into ASCII using the Punycode scheme.\nFor instance, the Japanese character that translates into the English word,\n'example'
is '例'
. The Internationalized Domain Name, '例.com'
(equivalent\nto 'example.com'
) is represented by Punycode as the ASCII string\n'xn--fsq.com'
.
The punycode
module provides a simple implementation of the Punycode standard.
Note: The punycode
module is a third-party dependency used by Node.js and\nmade available to developers as a convenience. Fixes or other modifications to\nthe module must be directed to the Punycode.js project.
The punycode.decode()
method converts a Punycode string of ASCII-only\ncharacters to the equivalent string of Unicode codepoints.
punycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'\n
\n"
},
{
"textRaw": "punycode.encode(string)",
"type": "method",
"name": "encode",
"meta": {
"added": [
"v0.5.1"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`string` {String} ",
"name": "string",
"type": "String"
}
]
},
{
"params": [
{
"name": "string"
}
]
}
],
"desc": "The punycode.encode()
method converts a string of Unicode codepoints to a\nPunycode string of ASCII-only characters.
punycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'\n
\n"
},
{
"textRaw": "punycode.toASCII(domain)",
"type": "method",
"name": "toASCII",
"meta": {
"added": [
"v0.6.1"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`domain` {String} ",
"name": "domain",
"type": "String"
}
]
},
{
"params": [
{
"name": "domain"
}
]
}
],
"desc": "The punycode.toASCII()
method converts a Unicode string representing an\nInternationalized Domain Name to Punycode. Only the non-ASCII parts of the\ndomain name will be converted. Calling punycode.toASCII()
on a string that\nalready only contains ASCII characters will have no effect.
// encode domain names\npunycode.toASCII('mañana.com'); // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'\npunycode.toASCII('example.com'); // 'example.com'\n
\n"
},
{
"textRaw": "punycode.toUnicode(domain)",
"type": "method",
"name": "toUnicode",
"meta": {
"added": [
"v0.6.1"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`domain` {String} ",
"name": "domain",
"type": "String"
}
]
},
{
"params": [
{
"name": "domain"
}
]
}
],
"desc": "The punycode.toUnicode()
method converts a string representing a domain name\ncontaining Punycode encoded characters into Unicode. Only the Punycode\nencoded parts of the domain name are be converted.
// decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'\npunycode.toUnicode('example.com'); // 'example.com'\n
\n"
}
],
"properties": [
{
"textRaw": "punycode.ucs2",
"name": "ucs2",
"meta": {
"added": [
"v0.7.0"
]
},
"modules": [
{
"textRaw": "punycode.ucs2.decode(string)",
"name": "punycode.ucs2.decode(string)",
"meta": {
"added": [
"v0.7.0"
]
},
"desc": "string
{String}The punycode.ucs2.decode()
method returns an array containing the numeric\ncodepoint values of each Unicode symbol in the string.
punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]\n
\n",
"type": "module",
"displayName": "punycode.ucs2.decode(string)"
},
{
"textRaw": "punycode.ucs2.encode(codePoints)",
"name": "punycode.ucs2.encode(codepoints)",
"meta": {
"added": [
"v0.7.0"
]
},
"desc": "codePoints
{Array}The punycode.ucs2.encode()
method returns a string based on an array of\nnumeric code point values.
punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'\n
\n",
"type": "module",
"displayName": "punycode.ucs2.encode(codePoints)"
}
]
},
{
"textRaw": "punycode.version",
"name": "version",
"meta": {
"added": [
"v0.6.1"
]
},
"desc": "Returns a string identifying the current Punycode.js version number.
\n\n\n" } ], "type": "module", "displayName": "punycode" }, { "textRaw": "Query String", "name": "querystring", "stability": 2, "stabilityText": "Stable", "desc": "The querystring
module provides utilities for parsing and formatting URL\nquery strings. It can be accessed using:
const querystring = require('querystring');\n
\n",
"methods": [
{
"textRaw": "querystring.escape(str)",
"type": "method",
"name": "escape",
"meta": {
"added": [
"v0.1.25"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`str` {String} ",
"name": "str",
"type": "String"
}
]
},
{
"params": [
{
"name": "str"
}
]
}
],
"desc": "The querystring.escape()
method performs URL percent-encoding on the given\nstr
in a manner that is optimized for the specific requirements of URL\nquery strings.
The querystring.escape()
method is used by querystring.stringify()
and is\ngenerally not expected to be used directly. It is exported primarily to allow\napplication code to provide a replacement percent-encoding implementation if\nnecessary by assigning querystring.escape
to an alternative function.
The querystring.parse()
method parses a URL query string (str
) into a\ncollection of key and value pairs.
For example, the query string 'foo=bar&abc=xyz&abc=123'
is parsed into:
{\n foo: 'bar',\n abc: ['xyz', '123']\n}\n
\nNote: The object returned by the querystring.parse()
method does not\nprototypically extend from the JavaScript Object
. This means that the\ntypical Object
methods such as obj.toString()
, obj.hasOwnProperty()
,\nand others are not defined and will not work.
By default, percent-encoded characters within the query string will be assumed\nto use UTF-8 encoding. If an alternative character encoding is used, then an\nalternative decodeURIComponent
option will need to be specified as illustrated\nin the following example:
// Assuming gbkDecodeURIComponent function already exists...\n\nquerystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,\n { decodeURIComponent: gbkDecodeURIComponent })\n
\n"
},
{
"textRaw": "querystring.stringify(obj[, sep[, eq[, options]]])",
"type": "method",
"name": "stringify",
"meta": {
"added": [
"v0.1.25"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`obj` {Object} The object to serialize into a URL query string ",
"name": "obj",
"type": "Object",
"desc": "The object to serialize into a URL query string"
},
{
"textRaw": "`sep` {String} The substring used to delimit key and value pairs in the query string. Defaults to `'&'`. ",
"name": "sep",
"type": "String",
"desc": "The substring used to delimit key and value pairs in the query string. Defaults to `'&'`.",
"optional": true
},
{
"textRaw": "`eq` {String}. The substring used to delimit keys and values in the query string. Defaults to `'='`. ",
"name": "eq",
"type": "String",
"desc": ". The substring used to delimit keys and values in the query string. Defaults to `'='`.",
"optional": true
},
{
"textRaw": "`options` ",
"options": [
{
"textRaw": "`encodeURIComponent` {Function} The function to use when converting URL-unsafe characters to percent-encoding in the query string. Defaults to `querystring.escape()`. ",
"name": "encodeURIComponent",
"type": "Function",
"desc": "The function to use when converting URL-unsafe characters to percent-encoding in the query string. Defaults to `querystring.escape()`."
}
],
"name": "options",
"optional": true
}
]
},
{
"params": [
{
"name": "obj"
},
{
"name": "sep",
"optional": true
},
{
"name": "eq",
"optional": true
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "The querystring.stringify()
method produces a URL query string from a\ngiven obj
by iterating through the object's "own properties".
For example:
\nquerystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })\n// returns 'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')\n// returns 'foo:bar;baz:qux'\n
\nBy default, characters requiring percent-encoding within the query string will\nbe encoded as UTF-8. If an alternative encoding is required, then an alternative\nencodeURIComponent
option will need to be specified as illustrated in the\nfollowing example:
// Assuming gbkEncodeURIComponent function already exists,\n\nquerystring.stringify({ w: '中文', foo: 'bar' }, null, null,\n { encodeURIComponent: gbkEncodeURIComponent })\n
\n"
},
{
"textRaw": "querystring.unescape(str)",
"type": "method",
"name": "unescape",
"meta": {
"added": [
"v0.1.25"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`str` {String} ",
"name": "str",
"type": "String"
}
]
},
{
"params": [
{
"name": "str"
}
]
}
],
"desc": "The querystring.unescape()
method performs decoding of URL percent-encoded\ncharacters on the given str
.
The querystring.unescape()
method is used by querystring.parse()
and is\ngenerally not expected to be used directly. It is exported primarily to allow\napplication code to provide a replacement decoding implementation if\nnecessary by assigning querystring.unescape
to an alternative function.
By default, the querystring.unescape()
method will attempt to use the\nJavaScript built-in decodeURIComponent()
method to decode. If that fails,\na safer equivalent that does not throw on malformed URLs will be used.
The readline
module provides an interface for reading data from a Readable\nstream (such as process.stdin
) one line at a time. It can be accessed using:
const readline = require('readline');\n
\nThe following simple example illustrates the basic use of the readline
module.
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
\nNote Once this code is invoked, the Node.js application will not\nterminate until the readline.Interface
is closed because the interface\nwaits for data to be received on the input
stream.
Instances of the readline.Interface
class are constructed using the\nreadline.createInterface()
method. Every instance is associated with a\nsingle input
Readable stream and a single output
Writable stream.\nThe output
stream is used to print prompts for user input that arrives on,\nand is read from, the input
stream.
The 'close'
event is emitted when one of the following occur:
rl.close()
method is called and the readline.Interface
instance has\nrelinquished control over the input
and output
streams;input
stream receives its 'end'
event;input
stream receives <ctrl>-D
to signal end-of-transmission (EOT);input
stream receives <ctrl>-C
to signal SIGINT
and there is no\nSIGINT
event listener registered on the readline.Interface
instance.The listener function is called without passing any arguments.
\nThe readline.Interface
instance should be considered to be "finished" once\nthe 'close'
event is emitted.
The 'line'
event is emitted whenever the input
stream receives an\nend-of-line input (\\n
, \\r
, or \\r\\n
). This usually occurs when the user\npresses the <Enter>
, or <Return>
keys.
The listener function is called with a string containing the single line of\nreceived input.
\nFor example:
\nrl.on('line', (input) => {\n console.log(`Received: ${input}`);\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'pause'",
"type": "event",
"name": "pause",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "The 'pause'
event is emitted when one of the following occur:
input
stream is paused.input
stream is not paused and receives the SIGCONT
event. (See\nevents SIGTSTP
and SIGCONT
)The listener function is called without passing any arguments.
\nFor example:
\nrl.on('pause', () => {\n console.log('Readline paused.');\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'resume'",
"type": "event",
"name": "resume",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "The 'resume'
event is emitted whenever the input
stream is resumed.
The listener function is called without passing any arguments.
\nrl.on('resume', () => {\n console.log('Readline resumed.');\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'SIGCONT'",
"type": "event",
"name": "SIGCONT",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "The 'SIGCONT'
event is emitted when a Node.js process previously moved into\nthe background using <ctrl>-Z
(i.e. SIGTSTP
) is then brought back to the\nforeground using fg(1).
If the input
stream was paused before the SIGTSTP
request, this event will\nnot be emitted.
The listener function is invoked without passing any arguments.
\nFor example:
\nrl.on('SIGCONT', () => {\n // `prompt` will automatically resume the stream\n rl.prompt();\n});\n
\nNote: The 'SIGCONT'
event is not supported on Windows.
The 'SIGINT'
event is emitted whenever the input
stream receives a\n<ctrl>-C
input, known typically as SIGINT
. If there are no 'SIGINT'
event\nlisteners registered when the input
stream receives a SIGINT
, the 'pause'
\nevent will be emitted.
The listener function is invoked without passing any arguments.
\nFor example:
\nrl.on('SIGINT', () => {\n rl.question('Are you sure you want to exit?', (answer) => {\n if (answer.match(/^y(es)?$/i)) rl.pause();\n });\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'SIGTSTP'",
"type": "event",
"name": "SIGTSTP",
"meta": {
"added": [
"v0.7.5"
]
},
"desc": "The 'SIGTSTP'
event is emitted when the input
stream receives a <ctrl>-Z
\ninput, typically known as SIGTSTP
. If there are no SIGTSTP
event listeners\nregistered when the input
stream receives a SIGTSTP
, the Node.js process\nwill be sent to the background.
When the program is resumed using fg(1), the 'pause'
and SIGCONT
events\nwill be emitted. These can be used to resume the input
stream.
The 'pause'
and 'SIGCONT'
events will not be emitted if the input
was\npaused before the process was sent to the background.
The listener function is invoked without passing any arguments.
\nFor example:
\nrl.on('SIGTSTP', () => {\n // This will override SIGTSTP and prevent the program from going to the\n // background.\n console.log('Caught SIGTSTP.');\n});\n
\nNote: The 'SIGTSTP'
event is not supported on Windows.
The rl.close()
method closes the readline.Interface
instance and\nrelinquishes control over the input
and output
streams. When called,\nthe 'close'
event will be emitted.
The rl.pause()
method pauses the input
stream, allowing it to be resumed\nlater if necessary.
Calling rl.pause()
does not immediately pause other events (including\n'line'
) from being emitted by the readline.Interface
instance.
The rl.prompt()
method writes the readline.Interface
instances configured\nprompt
to a new line in output
in order to provide a user with a new\nlocation at which to provide input.
When called, rl.prompt()
will resume the input
stream if it has been\npaused.
If the readline.Interface
was created with output
set to null
or\nundefined
the prompt is not written.
The rl.question()
method displays the query
by writing it to the output
,\nwaits for user input to be provided on input
, then invokes the callback
\nfunction passing the provided input as the first argument.
When called, rl.question()
will resume the input
stream if it has been\npaused.
If the readline.Interface
was created with output
set to null
or\nundefined
the query
is not written.
Example usage:
\nrl.question('What is your favorite food?', (answer) => {\n console.log(`Oh, so your favorite food is ${answer}`);\n});\n
\nNote: The callback
function passed to rl.question()
does not follow the\ntypical pattern of accepting an Error
object or null
as the first argument.\nThe callback
is called with the provided answer as the only argument.
The rl.resume()
method resumes the input
stream if it has been paused.
The rl.setPrompt()
method sets the prompt that will be written to output
\nwhenever rl.prompt()
is called.
The rl.write()
method will write either data
or a key sequence identified\nby key
to the output
. The key
argument is supported only if output
is\na TTY text terminal.
If key
is specified, data
is ignored.
When called, rl.write()
will resume the input
stream if it has been\npaused.
If the readline.Interface
was created with output
set to null
or\nundefined
the data
and key
are not written.
For example:
\nrl.write('Delete this!');\n// Simulate Ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});\n
\nNote: The rl.write()
method will write the data to the readline
\nInterface's input
as if it were provided by the user.
The readline.clearLine()
method clears current line of given TTY stream\nin a specified direction identified by dir
.
The readline.clearScreenDown()
method clears the given TTY stream from\nthe current position of the cursor down.
The readline.createInterface()
method creates a new readline.Interface
\ninstance.
For example:
\nconst readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n});\n
\nOnce the readline.Interface
instance is created, the most common case is to\nlisten for the 'line'
event:
rl.on('line', (line) => {\n console.log(`Received: ${line}`);\n});\n
\nIf terminal
is true
for this instance then the output
stream will get\nthe best compatibility if it defines an output.columns
property and emits\na 'resize'
event on the output
if or when the columns ever change\n(process.stdout
does this automatically when it is a TTY).
When called, the completer
function is provided the current line entered by\nthe user, and is expected to return an Array with 2 entries:
For instance: [[substr1, substr2, ...], originalsubstring]
.
function completer(line) {\n const completions = '.help .error .exit .quit .q'.split(' ');\n const 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
\nThe completer
function can be called asynchronously if it accepts two\narguments:
function completer(linePartial, callback) {\n callback(null, [['123'], linePartial]);\n}\n
\n",
"type": "module",
"displayName": "Use of the `completer` Function"
}
]
},
{
"textRaw": "readline.cursorTo(stream, x, y)",
"type": "method",
"name": "cursorTo",
"meta": {
"added": [
"v0.7.7"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`stream` {Writable} ",
"name": "stream",
"type": "Writable"
},
{
"textRaw": "`x` {number} ",
"name": "x",
"type": "number"
},
{
"textRaw": "`y` {number} ",
"name": "y",
"type": "number"
}
]
},
{
"params": [
{
"name": "stream"
},
{
"name": "x"
},
{
"name": "y"
}
]
}
],
"desc": "The readline.cursorTo()
method moves cursor to the specified position in a\ngiven TTY stream
.
The readline.emitKeypressEvents()
method causes the given Writable\nstream
to begin emitting 'keypress'
events corresponding to received input.
Optionally, interface
specifies a readline.Interface
instance for which\nautocompletion is disabled when copy-pasted input is detected.
If the stream
is a TTY, then it must be in raw mode.
readline.emitKeypressEvents(process.stdin);\nif (process.stdin.isTTY)\n process.stdin.setRawMode(true);\n
\n"
},
{
"textRaw": "readline.moveCursor(stream, dx, dy)",
"type": "method",
"name": "moveCursor",
"meta": {
"added": [
"v0.7.7"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`stream` {Writable} ",
"name": "stream",
"type": "Writable"
},
{
"textRaw": "`dx` {number} ",
"name": "dx",
"type": "number"
},
{
"textRaw": "`dy` {Number} ",
"name": "dy",
"type": "Number"
}
]
},
{
"params": [
{
"name": "stream"
},
{
"name": "dx"
},
{
"name": "dy"
}
]
}
],
"desc": "The readline.moveCursor()
method moves the cursor relative to its current\nposition in a given TTY stream
.
The following example illustrates the use of readline.Interface
class to\nimplement a small command-line interface:
const readline = require('readline');\nconst rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n prompt: 'OHAI> '\n});\n\nrl.prompt();\n\nrl.on('line', (line) => {\n switch(line.trim()) {\n case 'hello':\n console.log('world!');\n break;\n default:\n console.log(`Say what? I might have heard '${line.trim()}'`);\n break;\n }\n rl.prompt();\n}).on('close', () => {\n console.log('Have a great day!');\n process.exit(0);\n});\n
\nA common use case for readline
is to consume input from a filesystem\nReadable stream one line at a time, as illustrated in the following\nexample:
const readline = require('readline');\nconst fs = require('fs');\n\nconst rl = readline.createInterface({\n input: fs.createReadStream('sample.txt')\n});\n\nrl.on('line', (line) => {\n console.log(`Line from file: ${line}`);\n});\n
\n\n\n"
}
],
"type": "module",
"displayName": "Readline"
},
{
"textRaw": "REPL",
"name": "repl",
"stability": 2,
"stabilityText": "Stable",
"desc": "The repl
module provides a Read-Eval-Print-Loop (REPL) implementation that\nis available both as a standalone program or includible in other applications.\nIt can be accessed using:
const repl = require('repl');\n
\n",
"modules": [
{
"textRaw": "Design and Features",
"name": "design_and_features",
"desc": "The repl
module exports the repl.REPLServer
class. While running, instances\nof repl.REPLServer
will accept individual lines of user input, evaluate those\naccording to a user-defined evaluation function, then output the result. Input\nand output may be from stdin
and stdout
, respectively, or may be connected\nto any Node.js stream.
Instances of repl.REPLServer
support automatic completion of inputs,\nsimplistic Emacs-style line editing, multi-line inputs, ANSI-styled output,\nsaving and restoring current REPL session state, error recovery, and\ncustomizable evaluation functions.
The following special commands are supported by all REPL instances:
\n.break
- When in the process of inputting a multi-line expression, entering\nthe .break
command (or pressing the <ctrl>-C
key combination) will abort\nfurther input or processing of that expression..clear
- Resets the REPL context
to an empty object and clears any\nmulti-line expression currently being input..exit
- Close the I/O stream, causing the REPL to exit..help
- Show this list of special commands..save
- Save the current REPL session to a file:\n> .save ./file/to/save.js
.load
- Load a file into the current REPL session.\n> .load ./file/to/load.js
.editor
- Enter editor mode (<ctrl>-D
to finish, <ctrl>-C
to cancel)> .editor\n// Entering editor mode (^D to finish, ^C to cancel)\nfunction welcome(name) {\n return `Hello ${name}!`;\n}\n\nwelcome('Node.js User');\n\n// ^D\n'Hello Node.js User!'\n>\n
\nThe following key combinations in the REPL have these special effects:
\n<ctrl>-C
- When pressed once, has the same effect as the .break
command.\nWhen pressed twice on a blank line, has the same effect as the .exit
\ncommand.<ctrl>-D
- Has the same effect as the .exit
command.<tab>
- When pressed on a blank line, displays global and local(scope)\nvariables. When pressed while entering other input, displays relevant\nautocompletion options.By default, all instances of repl.REPLServer
use an evaluation function that\nevaluates JavaScript expressions and provides access to Node.js' built-in\nmodules. This default behavior can be overridden by passing in an alternative\nevaluation function when the repl.REPLServer
instance is created.
The default evaluator supports direct evaluation of JavaScript expressions:
\n> 1 + 1\n2\n> const m = 2\nundefined\n> m + 1\n3\n
\nUnless otherwise scoped within blocks or functions, variables declared\neither implicitly or using the const
, let
, or var
keywords\nare declared at the global scope.
The default evaluator provides access to any variables that exist in the global\nscope. It is possible to expose a variable to the REPL explicitly by assigning\nit to the context
object associated with each REPLServer
. For example:
const repl = require('repl');\nconst msg = 'message';\n\nrepl.start('> ').context.m = msg;\n
\nProperties in the context
object appear as local within the REPL:
$ node repl_test.js\n> m\n'message'\n
\nIt is important to note that context properties are not read-only by default.\nTo specify read-only globals, context properties must be defined using\nObject.defineProperty()
:
const repl = require('repl');\nconst msg = 'message';\n\nconst r = repl.start('> ');\nObject.defineProperty(r.context, 'm', {\n configurable: false,\n enumerable: true,\n value: msg\n});\n
\n",
"type": "module",
"displayName": "Global and Local Scope"
},
{
"textRaw": "Accessing Core Node.js Modules",
"name": "accessing_core_node.js_modules",
"desc": "The default evaluator will automatically load Node.js core modules into the\nREPL environment when used. For instance, unless otherwise declared as a\nglobal or scoped variable, the input fs
will be evaluated on-demand as\nglobal.fs = require('fs')
.
> fs.createReadStream('./some/file');\n
\n",
"type": "module",
"displayName": "Accessing Core Node.js Modules"
},
{
"textRaw": "Assignment of the `_` (underscore) variable",
"name": "assignment_of_the_`_`_(underscore)_variable",
"desc": "The default evaluator will, by default, assign the result of the most recently\nevaluated expression to the special variable _
(underscore).\nExplicitly setting _
to a value will disable this behavior.
> [ 'a', 'b', 'c' ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\nExpression assignment to _ now disabled.\n4\n> 1 + 1\n2\n> _\n4\n
\n",
"type": "module",
"displayName": "Assignment of the `_` (underscore) variable"
}
],
"type": "module",
"displayName": "Default Evaluation"
},
{
"textRaw": "Custom Evaluation Functions",
"name": "custom_evaluation_functions",
"desc": "When a new repl.REPLServer
is created, a custom evaluation function may be\nprovided. This can be used, for instance, to implement fully customized REPL\napplications.
The following illustrates a hypothetical example of a REPL that performs\ntranslation of text from one language to another:
\nconst repl = require('repl');\nconst Translator = require('translator').Translator;\n\nconst myTranslator = new Translator('en', 'fr');\n\nfunction myEval(cmd, context, filename, callback) {\n callback(null, myTranslator.translate(cmd));\n}\n\nrepl.start({prompt: '> ', eval: myEval});\n
\n",
"modules": [
{
"textRaw": "Recoverable Errors",
"name": "recoverable_errors",
"desc": "As a user is typing input into the REPL prompt, pressing the <enter>
key will\nsend the current line of input to the eval
function. In order to support\nmulti-line input, the eval function can return an instance of repl.Recoverable
\nto the provided callback function:
function myEval(cmd, context, filename, callback) {\n let result;\n try {\n result = vm.runInThisContext(cmd);\n } catch (e) {\n if (isRecoverableError(e)) {\n return callback(new repl.Recoverable(e));\n }\n }\n callback(null, result);\n}\n\nfunction isRecoverableError(error) {\n if (error.name === 'SyntaxError') {\n return /^(Unexpected end of input|Unexpected token)/.test(error.message);\n }\n return false;\n}\n
\n",
"type": "module",
"displayName": "Recoverable Errors"
}
],
"type": "module",
"displayName": "Custom Evaluation Functions"
},
{
"textRaw": "Customizing REPL Output",
"name": "customizing_repl_output",
"desc": "By default, repl.REPLServer
instances format output using the\nutil.inspect()
method before writing the output to the provided Writable\nstream (process.stdout
by default). The useColors
boolean option can be\nspecified at construction to instruct the default writer to use ANSI style\ncodes to colorize the output from the util.inspect()
method.
It is possible to fully customize the output of a repl.REPLServer
instance\nby passing a new function in using the writer
option on construction. The\nfollowing example, for instance, simply converts any input text to upper case:
const repl = require('repl');\n\nconst r = repl.start({prompt: '> ', eval: myEval, writer: myWriter});\n\nfunction myEval(cmd, context, filename, callback) {\n callback(null, cmd);\n}\n\nfunction myWriter(output) {\n return output.toUpperCase();\n}\n
\n",
"type": "module",
"displayName": "Customizing REPL Output"
}
],
"type": "module",
"displayName": "Design and Features"
},
{
"textRaw": "The Node.js REPL",
"name": "the_node.js_repl",
"desc": "Node.js itself uses the repl
module to provide its own interactive interface\nfor executing JavaScript. This can be used by executing the Node.js binary\nwithout passing any arguments (or by passing the -i
argument):
$ node\n> const a = [1, 2, 3];\n[ 1, 2, 3 ]\n> a.forEach((v) => {\n... console.log(v);\n... });\n1\n2\n3\n
\n",
"modules": [
{
"textRaw": "Environment Variable Options",
"name": "environment_variable_options",
"desc": "Various behaviors of the Node.js REPL can be customized using the following\nenvironment variables:
\nNODE_REPL_HISTORY
- When a valid path is given, persistent REPL history\nwill be saved to the specified file rather than .node_repl_history
in the\nuser's home directory. Setting this value to ""
will disable persistent\nREPL history. Whitespace will be trimmed from the value.NODE_REPL_HISTORY_SIZE
- Defaults to 1000
. Controls how many lines of\nhistory will be persisted if history is available. Must be a positive number.NODE_REPL_MODE
- May be any of sloppy
, strict
, or magic
. Defaults\nto magic
, which will automatically run "strict mode only" statements in\nstrict mode.By default, the Node.js REPL will persist history between node
REPL sessions\nby saving inputs to a .node_repl_history
file located in the user's home\ndirectory. This can be disabled by setting the environment variable\nNODE_REPL_HISTORY=""
.
Previously in Node.js/io.js v2.x, REPL history was controlled by using a\nNODE_REPL_HISTORY_FILE
environment variable, and the history was saved in JSON\nformat. This variable has now been deprecated, and the old JSON REPL history\nfile will be automatically converted to a simplified plain text format. This new\nfile will be saved to either the user's home directory, or a directory defined\nby the NODE_REPL_HISTORY
variable, as documented in the\nEnvironment Variable Options.
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
.
For example, you could add this to your bashrc file:
\nalias node="env NODE_NO_READLINE=1 rlwrap node"\n
\n",
"type": "module",
"displayName": "Using the Node.js REPL with advanced line-editors"
},
{
"textRaw": "Starting multiple REPL instances against a single running instance",
"name": "starting_multiple_repl_instances_against_a_single_running_instance",
"desc": "It is possible to create and run multiple REPL instances against a single\nrunning instance of Node.js that share a single global
object but have\nseparate I/O interfaces.
The following example, for instance, provides separate REPLs on stdin
, a Unix\nsocket, and a TCP socket:
const net = require('net');\nconst repl = require('repl');\nlet connections = 0;\n\nrepl.start({\n prompt: 'Node.js via stdin> ',\n input: process.stdin,\n output: process.stdout\n});\n\nnet.createServer((socket) => {\n connections += 1;\n repl.start({\n prompt: 'Node.js via Unix socket> ',\n input: socket,\n output: socket\n }).on('exit', () => {\n socket.end();\n });\n}).listen('/tmp/node-repl-sock');\n\nnet.createServer((socket) => {\n connections += 1;\n repl.start({\n prompt: 'Node.js via TCP socket> ',\n input: socket,\n output: socket\n }).on('exit', () => {\n socket.end();\n });\n}).listen(5001);\n
\nRunning this application from the command line will start a REPL on stdin.\nOther REPL clients may connect through the Unix socket or TCP socket. telnet
,\nfor instance, is useful for connecting to TCP sockets, while socat
can be used\nto connect to both Unix and TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, it is\npossible to connect to a long-running Node.js process without restarting it.
\nFor an example of running a "full-featured" (terminal
) REPL over\na net.Server
and net.Socket
instance, see: https://gist.github.com/2209310
For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342
\n\n\n", "type": "module", "displayName": "Starting multiple REPL instances against a single running instance" } ], "type": "module", "displayName": "The Node.js REPL" } ], "classes": [ { "textRaw": "Class: REPLServer", "type": "class", "name": "REPLServer", "meta": { "added": [ "v0.1.91" ] }, "desc": "The repl.REPLServer
class inherits from the readline.Interface
class.\nInstances of repl.REPLServer
are created using the repl.start()
method and\nshould not be created directly using the JavaScript new
keyword.
The 'exit'
event is emitted when the REPL is exited either by receiving the\n.exit
command as input, the user pressing <ctrl>-C
twice to signal SIGINT
,\nor by pressing <ctrl>-D
to signal 'end'
on the input stream. The listener\ncallback is invoked without any arguments.
replServer.on('exit', () => {\n console.log('Received "exit" event from repl!');\n process.exit();\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'reset'",
"type": "event",
"name": "reset",
"meta": {
"added": [
"v0.11.0"
]
},
"desc": "The 'reset'
event is emitted when the REPL's context is reset. This occurs\nwhenever the .clear
command is received as input unless the REPL is using\nthe default evaluator and the repl.REPLServer
instance was created with the\nuseGlobal
option set to true
. The listener callback will be called with a\nreference to the context
object as the only argument.
This can be used primarily to re-initialize REPL context to some pre-defined\nstate as illustrated in the following simple example:
\nconst repl = require('repl');\n\nfunction initializeContext(context) {\n context.m = 'test';\n}\n\nconst r = repl.start({prompt: '> '});\ninitializeContext(r.context);\n\nr.on('reset', initializeContext);\n
\nWhen this code is executed, the global 'm'
variable can be modified but then\nreset to its initial value using the .clear
command:
$ ./node example.js\n> m\n'test'\n> m = 1\n1\n> m\n1\n> .clear\nClearing context...\n> m\n'test'\n>\n
\n",
"params": []
}
],
"methods": [
{
"textRaw": "replServer.defineCommand(keyword, cmd)",
"type": "method",
"name": "defineCommand",
"meta": {
"added": [
"v0.3.0"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`keyword` {String} The command keyword (*without* a leading `.` character). ",
"name": "keyword",
"type": "String",
"desc": "The command keyword (*without* a leading `.` character)."
},
{
"textRaw": "`cmd` {Object|Function} The function to invoke when the command is processed. ",
"name": "cmd",
"type": "Object|Function",
"desc": "The function to invoke when the command is processed."
}
]
},
{
"params": [
{
"name": "keyword"
},
{
"name": "cmd"
}
]
}
],
"desc": "The replServer.defineCommand()
method is used to add new .
-prefixed commands\nto the REPL instance. Such commands are invoked by typing a .
followed by the\nkeyword
. The cmd
is either a Function or an object with the following\nproperties:
help
{String} Help text to be displayed when .help
is entered (Optional).action
{Function} The function to execute, optionally accepting a single\nstring argument.The following example shows two new commands added to the REPL instance:
\nconst repl = require('repl');\n\nconst replServer = repl.start({prompt: '> '});\nreplServer.defineCommand('sayhello', {\n help: 'Say hello',\n action(name) {\n this.lineParser.reset();\n this.bufferedCommand = '';\n console.log(`Hello, ${name}!`);\n this.displayPrompt();\n }\n});\nreplServer.defineCommand('saybye', () => {\n console.log('Goodbye!');\n this.close();\n});\n
\nThe new commands can then be used from within the REPL instance:
\n> .sayhello Node.js User\nHello, Node.js User!\n> .saybye\nGoodbye!\n
\n"
},
{
"textRaw": "replServer.displayPrompt([preserveCursor])",
"type": "method",
"name": "displayPrompt",
"meta": {
"added": [
"v0.1.91"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`preserveCursor` {Boolean} ",
"name": "preserveCursor",
"type": "Boolean",
"optional": true
}
]
},
{
"params": [
{
"name": "preserveCursor",
"optional": true
}
]
}
],
"desc": "The replServer.displayPrompt()
method readies the REPL instance for input\nfrom the user, printing the configured prompt
to a new line in the output
\nand resuming the input
to accept new input.
When multi-line input is being entered, an ellipsis is printed rather than the\n'prompt'.
\nWhen preserveCursor
is true
, the cursor placement will not be reset to 0
.
The replServer.displayPrompt
method is primarily intended to be called from\nwithin the action function for commands registered using the\nreplServer.defineCommand()
method.
The repl.start()
method creates and starts a repl.REPLServer
instance.
If options
is a string, then it specifies the input prompt:
const repl = require('repl');\n\n// a Unix style prompt\nrepl.start('$ ');\n
\n"
}
],
"type": "module",
"displayName": "REPL"
},
{
"textRaw": "Stream",
"name": "stream",
"stability": 2,
"stabilityText": "Stable",
"desc": "A stream is an abstract interface for working with streaming data in Node.js.\nThe stream
module provides a base API that makes it easy to build objects\nthat implement the stream interface.
There are many stream objects provided by Node.js. For instance, a\nrequest to an HTTP server and process.stdout
\nare both stream instances.
Streams can be readable, writable, or both. All streams are instances of\nEventEmitter
.
The stream
module can be accessed using:
const stream = require('stream');\n
\nWhile it is important for all Node.js users to understand how streams work,\nthe stream
module itself is most useful for developers that are creating new\ntypes of stream instances. Developer's who are primarily consuming stream\nobjects will rarely (if ever) have need to use the stream
module directly.
This document is divided into two primary sections with a third section for\nadditional notes. The first section explains the elements of the stream API that\nare required to use streams within an application. The second section explains\nthe elements of the API that are required to implement new types of streams.
\n", "type": "module", "displayName": "Organization of this Document" }, { "textRaw": "Types of Streams", "name": "types_of_streams", "desc": "There are four fundamental stream types within Node.js:
\nfs.createReadStream()
).fs.createWriteStream()
).net.Socket
).zlib.createDeflate()
).All streams created by Node.js APIs operate exclusively on strings and Buffer
\nobjects. It is possible, however, for stream implementations to work with other\ntypes of JavaScript values (with the exception of null
, which serves a special\npurpose within streams). Such streams are considered to operate in "object\nmode".
Stream instances are switched into object mode using the objectMode
option\nwhen the stream is created. Attempting to switch an existing stream into\nobject mode is not safe.
Both Writable and Readable streams will store data in an internal\nbuffer that can be retrieved using writable._writableState.getBuffer()
or\nreadable._readableState.buffer
, respectively.
The amount of data potentially buffered depends on the highWaterMark
option\npassed into the streams constructor. For normal streams, the highWaterMark
\noption specifies a total number of bytes. For streams operating in object mode,\nthe highWaterMark
specifies a total number of objects.
Data is buffered in Readable streams when the implementation calls\nstream.push(chunk)
. If the consumer of the Stream does not\ncall stream.read()
, the data will sit in the internal\nqueue until it is consumed.
Once the total size of the internal read buffer reaches the threshold specified\nby highWaterMark
, the stream will temporarily stop reading data from the\nunderlying resource until the data currently buffered can be consumed (that is,\nthe stream will stop calling the internal readable._read()
method that is\nused to fill the read buffer).
Data is buffered in Writable streams when the\nwritable.write(chunk)
method is called repeatedly. While the\ntotal size of the internal write buffer is below the threshold set by\nhighWaterMark
, calls to writable.write()
will return true
. Once\nthe size of the internal buffer reaches or exceeds the highWaterMark
, false
\nwill be returned.
A key goal of the stream
API, particularly the stream.pipe()
method,\nis to limit the buffering of data to acceptable levels such that sources and\ndestinations of differing speeds will not overwhelm the available memory.
Because Duplex and Transform streams are both Readable and Writable,\neach maintain two separate internal buffers used for reading and writing,\nallowing each side to operate independently of the other while maintaining an\nappropriate and efficient flow of data. For example, net.Socket
instances\nare Duplex streams whose Readable side allows consumption of data received\nfrom the socket and whose Writable side allows writing data to the socket.\nBecause data may be written to the socket at a faster or slower rate than data\nis received, it is important for each side to operate (and buffer) independently\nof the other.
Almost all Node.js applications, no matter how simple, use streams in some\nmanner. The following is an example of using streams in a Node.js application\nthat implements an HTTP server:
\nconst http = require('http');\n\nconst server = http.createServer( (req, res) => {\n // req is an http.IncomingMessage, which is a Readable Stream\n // res is an http.ServerResponse, which is a Writable Stream\n\n let body = '';\n // Get the data as utf8 strings.\n // If an encoding is not set, Buffer objects will be received.\n req.setEncoding('utf8');\n\n // Readable streams emit 'data' events once a listener is added\n req.on('data', (chunk) => {\n body += chunk;\n });\n\n // the end event indicates that the entire body has been received\n req.on('end', () => {\n try {\n const data = JSON.parse(body);\n // write back something interesting to the user:\n res.write(typeof data);\n res.end();\n } catch (er) {\n // uh oh! bad json!\n res.statusCode = 400;\n return res.end(`error: ${er.message}`);\n }\n });\n});\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d '{}'\n// object\n// $ curl localhost:1337 -d '"foo"'\n// string\n// $ curl localhost:1337 -d 'not json'\n// error: Unexpected token o\n
\nWritable streams (such as res
in the example) expose methods such as\nwrite()
and end()
that are used to write data onto the stream.
Readable streams use the EventEmitter
API for notifying application\ncode when data is available to be read off the stream. That available data can\nbe read from the stream in multiple ways.
Both Writable and Readable streams use the EventEmitter
API in\nvarious ways to communicate the current state of the stream.
Duplex and Transform streams are both Writable and Readable.
\nApplications that are either writing data to or consuming data from a stream\nare not required to implement the stream interfaces directly and will generally\nhave no reason to call require('stream')
.
Developers wishing to implement new types of streams should refer to the\nsection API for Stream Implementers.
\n", "miscs": [ { "textRaw": "Writable Streams", "name": "writable_streams", "desc": "Writable streams are an abstraction for a destination to which data is\nwritten.
\nExamples of Writable streams include:
\nprocess.stdout
, process.stderr
Note: Some of these examples are actually Duplex streams that implement\nthe Writable interface.
\nAll Writable streams implement the interface defined by the\nstream.Writable
class.
While specific instances of Writable streams may differ in various ways,\nall Writable streams follow the same fundamental usage pattern as illustrated\nin the example below:
\nconst myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n
\n",
"classes": [
{
"textRaw": "Class: stream.Writable",
"type": "class",
"name": "stream.Writable",
"meta": {
"added": [
"v0.9.4"
]
},
"events": [
{
"textRaw": "Event: 'close'",
"type": "event",
"name": "close",
"meta": {
"added": [
"v0.9.4"
]
},
"desc": "The 'close'
event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.
Not all Writable streams will emit the 'close'
event.
If a call to stream.write(chunk)
returns false
, the\n'drain'
event will be emitted when it is appropriate to resume writing data\nto the stream.
// Write the data to the supplied writable stream one million times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n let i = 1000000;\n write();\n function write() {\n var ok = true;\n do {\n i--;\n if (i === 0) {\n // last time!\n writer.write(data, encoding, callback);\n } else {\n // see if we should continue, or wait\n // don't pass the callback, because we're not done yet.\n ok = writer.write(data, encoding);\n }\n } while (i > 0 && ok);\n if (i > 0) {\n // had to stop early!\n // write some more once it drains\n writer.once('drain', write);\n }\n }\n}\n
\n",
"params": []
},
{
"textRaw": "Event: 'error'",
"type": "event",
"name": "error",
"meta": {
"added": [
"v0.9.4"
]
},
"params": [],
"desc": "The 'error'
event is emitted if an error occurred while writing or piping\ndata. The listener callback is passed a single Error
argument when called.
Note: The stream is not closed when the 'error'
event is emitted.
The 'finish'
event is emitted after the stream.end()
method\nhas been called, and all data has been flushed to the underlying system.
const writer = getWritableStreamSomehow();\nfor (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
\n",
"params": []
},
{
"textRaw": "Event: 'pipe'",
"type": "event",
"name": "pipe",
"meta": {
"added": [
"v0.9.4"
]
},
"params": [],
"desc": "The 'pipe'
event is emitted when the stream.pipe()
method is called on\na readable stream, adding this writable to its set of destinations.
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('pipe', (src) => {\n console.error('something is piping into the writer');\n assert.equal(src, reader);\n});\nreader.pipe(writer);\n
\n"
},
{
"textRaw": "Event: 'unpipe'",
"type": "event",
"name": "unpipe",
"meta": {
"added": [
"v0.9.4"
]
},
"params": [],
"desc": "The 'unpipe'
event is emitted when the stream.unpipe()
method is called\non a Readable stream, removing this Writable from its set of\ndestinations.
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('unpipe', (src) => {\n console.error('Something has stopped piping into the writer.');\n assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);\n
\n"
}
],
"methods": [
{
"textRaw": "writable.cork()",
"type": "method",
"name": "cork",
"meta": {
"added": [
"v0.11.2"
]
},
"desc": "The writable.cork()
method forces all written data to be buffered in memory.\nThe buffered data will be flushed when either the stream.uncork()
or\nstream.end()
methods are called.
The primary intent of writable.cork()
is to avoid a situation where writing\nmany small chunks of data to a stream do not cause a backup in the internal\nbuffer that would have an adverse impact on performance. In such situations,\nimplementations that implement the writable._writev()
method can perform\nbuffered writes in a more optimized manner.
Calling the writable.end()
method signals that no more data will be written\nto the Writable. The optional chunk
and encoding
arguments allow one\nfinal additional chunk of data to be written immediately before closing the\nstream. If provided, the optional callback
function is attached as a listener\nfor the 'finish'
event.
Calling the stream.write()
method after calling\nstream.end()
will raise an error.
// write 'hello, ' and then end with 'world!'\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// writing more now is not allowed!\n
\n"
},
{
"textRaw": "writable.setDefaultEncoding(encoding)",
"type": "method",
"name": "setDefaultEncoding",
"meta": {
"added": [
"v0.11.15"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: `this` ",
"name": "return",
"desc": "`this`"
},
"params": [
{
"textRaw": "`encoding` {String} The new default encoding ",
"name": "encoding",
"type": "String",
"desc": "The new default encoding"
}
]
},
{
"params": [
{
"name": "encoding"
}
]
}
],
"desc": "The writable.setDefaultEncoding()
method sets the default encoding
for a\nWritable stream.
The writable.uncork()
method flushes all data buffered since\nstream.cork()
was called.
When using writable.cork()
and writable.uncork()
to manage the buffering\nof writes to a stream, it is recommended that calls to writable.uncork()
be\ndeferred using process.nextTick()
. Doing so allows batching of all\nwritable.write()
calls that occur within a given Node.js event loop phase.
stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n
\nIf the writable.cork()
method is called multiple times on a stream, the same\nnumber of calls to writable.uncork()
must be called to flush the buffered\ndata.
stream.cork();\nstream.write('some ');\nstream.cork();\nstream.write('data ');\nprocess.nextTick(() => {\n stream.uncork();\n // The data will not be flushed until uncork() is called a second time.\n stream.uncork();\n});\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "writable.write(chunk[, encoding][, callback])",
"type": "method",
"name": "write",
"meta": {
"added": [
"v0.9.4"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. ",
"name": "return",
"type": "Boolean",
"desc": "`false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`."
},
"params": [
{
"textRaw": "`chunk` {String|Buffer} The data to write ",
"name": "chunk",
"type": "String|Buffer",
"desc": "The data to write"
},
{
"textRaw": "`encoding` {String} The encoding, if `chunk` is a String ",
"name": "encoding",
"type": "String",
"desc": "The encoding, if `chunk` is a String",
"optional": true
},
{
"textRaw": "`callback` {Function} Callback for when this chunk of data is flushed ",
"name": "callback",
"type": "Function",
"desc": "Callback for when this chunk of data is flushed",
"optional": true
}
]
},
{
"params": [
{
"name": "chunk"
},
{
"name": "encoding",
"optional": true
},
{
"name": "callback",
"optional": true
}
]
}
],
"desc": "The writable.write()
method writes some data to the stream, and calls the\nsupplied callback
once the data has been fully handled. If an error\noccurs, the callback
may or may not be called with the error as its\nfirst argument. To reliably detect write errors, add a listener for the\n'error'
event.
The return value is true
if the internal buffer is less than the\nhighWaterMark
configured when the stream was created after admitting chunk
.\nIf false
is returned, further attempts to write data to the stream should\nstop until the 'drain'
event is emitted.
While a stream is not draining, calls to write()
will buffer chunk
, and\nreturn false. Once all currently buffered chunks are drained (accepted for\ndelivery by the operating system), the 'drain'
event will be emitted.\nIt is recommended that once write() returns false, no more chunks be written\nuntil the 'drain'
event is emitted. While calling write()
on a stream that\nis not draining is allowed, Node.js will buffer all written chunks until\nmaximum memory usage occurs, at which point it will abort unconditionally.\nEven before it aborts, high memory usage will cause poor garbage collector\nperformance and high RSS (which is not typically released back to the system,\neven after the memory is no longer required). Since TCP sockets may never\ndrain if the remote peer does not read the data, writing a socket that is\nnot draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly\nproblematic for a Transform, because the Transform
streams are paused\nby default until they are piped or an 'data'
or 'readable'
event handler\nis added.
If the data to be written can be generated or fetched on demand, it is\nrecommended to encapsulate the logic into a Readable and use\nstream.pipe()
. However, if calling write()
is preferred, it is\npossible to respect backpressure and avoid memory issues using the\nthe 'drain'
event:
function write (data, cb) {\n if (!stream.write(data)) {\n stream.once('drain', cb)\n } else {\n process.nextTick(cb)\n }\n}\n\n// Wait for cb to be called before doing any other write.\nwrite('hello', () => {\n console.log('write completed, do more writes now')\n})\n
\nA Writable stream in object mode will always ignore the encoding
argument.
Readable streams are an abstraction for a source from which data is\nconsumed.
\nExamples of Readable streams include:
\nprocess.stdin
All Readable streams implement the interface defined by the\nstream.Readable
class.
Readable streams effectively operate in one of two modes: flowing and paused.
\nWhen in flowing mode, data is read from the underlying system automatically\nand provided to an application as quickly as possible using events via the\nEventEmitter
interface.
In paused mode, the stream.read()
method must be called\nexplicitly to read chunks of data from the stream.
All Readable streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:
\n'data'
event handler.stream.resume()
method.stream.pipe()
method to send the data to a Writable.The Readable can switch back to paused mode using one of the following:
\nstream.pause()
method.'data'
event\nhandlers, and removing all pipe destinations by calling the\nstream.unpipe()
method.The important concept to remember is that a Readable will not generate data\nuntil a mechanism for either consuming or ignoring that data is provided. If\nthe consuming mechanism is disabled or taken away, the Readable will attempt\nto stop generating the data.
\nNote: For backwards compatibility reasons, removing 'data'
event\nhandlers will not automatically pause the stream. Also, if there are piped\ndestinations, then calling stream.pause()
will not guarantee\nthat the stream will remain paused once those destinations drain and ask for\nmore data.
Note: If a Readable is switched into flowing mode and there are no\nconsumers available handle the data, that data will be lost. This can occur,\nfor instance, when the readable.resume()
method is called without a listener\nattached to the 'data'
event, or when a 'data'
event handler is removed\nfrom the stream.
The "two modes" of operation for a Readable stream are a simplified abstraction\nfor the more complicated internal state management that is happening within the\nReadable stream implementation.
\nSpecifically, at any given point in time, every Readable is in one of three\npossible states:
\nreadable._readableState.flowing = null
readable._readableState.flowing = false
readable._readableState.flowing = true
When readable._readableState.flowing
is null
, no mechanism for consuming the\nstreams data is provided so the stream will not generate its data.
Attaching a listener for the 'data'
event, calling the readable.pipe()
\nmethod, or calling the readable.resume()
method will switch\nreadable._readableState.flowing
to true
, causing the Readable to begin\nactively emitting events as data is generated.
Calling readable.pause()
, readable.unpipe()
, or receiving "back pressure"\nwill cause the readable._readableState.flowing
to be set as false
,\ntemporarily halting the flowing of events but not halting the generation of\ndata.
While readable._readableState.flowing
is false
, data may be accumulating\nwithin the streams internal buffer.
The Readable stream API evolved across multiple Node.js versions and provides\nmultiple methods of consuming stream data. In general, developers should choose\none of the methods of consuming data and should never use multiple methods\nto consume data from a single stream.
\nUse of the readable.pipe()
method is recommended for most users as it has been\nimplemented to provide the easiest way of consuming stream data. Developers that\nrequire more fine-grained control over the transfer and generation of data can\nuse the EventEmitter
and readable.pause()
/readable.resume()
APIs.
The 'close'
event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.
Not all Readable streams will emit the 'close'
event.
The 'data'
event is emitted whenever the stream is relinquishing ownership of\na chunk of data to a consumer. This may occur whenever the stream is switched\nin flowing mode by calling readable.pipe()
, readable.resume()
, or by\nattaching a listener callback to the 'data'
event. The 'data'
event will\nalso be emitted whenever the readable.read()
method is called and a chunk of\ndata is available to be returned.
Attaching a 'data'
event listener to a stream that has not been explicitly\npaused will switch the stream into flowing mode. Data will then be passed as\nsoon as it is available.
The listener callback will be passed the chunk of data as a string if a default\nencoding has been specified for the stream using the\nreadable.setEncoding()
method; otherwise the data will be passed as a\nBuffer
.
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n});\n
\n"
},
{
"textRaw": "Event: 'end'",
"type": "event",
"name": "end",
"meta": {
"added": [
"v0.9.4"
]
},
"desc": "The 'end'
event is emitted when there is no more data to be consumed from\nthe stream.
Note: The 'end'
event will not be emitted unless the data is\ncompletely consumed. This can be accomplished by switching the stream into\nflowing mode, or by calling stream.read()
repeatedly until\nall data has been consumed.
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n});\nreadable.on('end', () => {\n console.log('There will be no more data.');\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'error'",
"type": "event",
"name": "error",
"meta": {
"added": [
"v0.9.4"
]
},
"params": [],
"desc": "The 'error'
event may be emitted by a Readable implementation at any time.\nTypically, this may occur if the underlying stream in unable to generate data\ndue to an underlying internal failure, or when a stream implementation attempts\nto push an invalid chunk of data.
The listener callback will be passed a single Error
object.
The 'readable'
event is emitted when there is data available to be read from\nthe stream. In some cases, attaching a listener for the 'readable'
event will\ncause some amount of data to be read into an internal buffer.
const readable = getReadableStreamSomehow();\nreadable.on('readable', () => {\n // there is some data to read now\n});\n
\nThe 'readable'
event will also be emitted once the end of the stream data\nhas been reached but before the 'end'
event is emitted.
Effectively, the 'readable'
event indicates that the stream has new\ninformation: either new data is available or the end of the stream has been\nreached. In the former case, stream.read()
will return the\navailable data. In the latter case, stream.read()
will return\nnull
. For instance, in the following example, foo.txt
is an empty file:
const fs = require('fs');\nconst rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n console.log('readable:', rr.read());\n});\nrr.on('end', () => {\n console.log('end');\n});\n
\nThe output of running this script is:
\n$ node test.js\nreadable: null\nend\n
\nNote: In general, the readable.pipe()
and 'data'
event mechanisms are\npreferred over the use of the 'readable'
event.
The readable.isPaused()
method returns the current operating state of the\nReadable. This is used primarily by the mechanism that underlies the\nreadable.pipe()
method. In most typical cases, there will be no reason to\nuse this method directly.
const readable = new stream.Readable\n\nreadable.isPaused() // === false\nreadable.pause()\nreadable.isPaused() // === true\nreadable.resume()\nreadable.isPaused() // === false\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "readable.pause()",
"type": "method",
"name": "pause",
"meta": {
"added": [
"v0.9.4"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: `this` ",
"name": "return",
"desc": "`this`"
},
"params": []
},
{
"params": []
}
],
"desc": "The readable.pause()
method will cause a stream in flowing mode to stop\nemitting 'data'
events, switching out of flowing mode. Any data that\nbecomes available will remain in the internal buffer.
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n readable.pause();\n console.log('There will be no additional data for 1 second.');\n setTimeout(() => {\n console.log('Now data will start flowing again.');\n readable.resume();\n }, 1000);\n});\n
\n"
},
{
"textRaw": "readable.pipe(destination[, options])",
"type": "method",
"name": "pipe",
"meta": {
"added": [
"v0.9.4"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`destination` {stream.Writable} The destination for writing data ",
"name": "destination",
"type": "stream.Writable",
"desc": "The destination for writing data"
},
{
"textRaw": "`options` {Object} Pipe options ",
"options": [
{
"textRaw": "`end` {Boolean} End the writer when the reader ends. Defaults to `true`. ",
"name": "end",
"type": "Boolean",
"desc": "End the writer when the reader ends. Defaults to `true`."
}
],
"name": "options",
"type": "Object",
"desc": "Pipe options",
"optional": true
}
]
},
{
"params": [
{
"name": "destination"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "The readable.pipe()
method attaches a Writable stream to the readable
,\ncausing it to switch automatically into flowing mode and push all of its data\nto the attached Writable. The flow of data will be automatically managed so\nthat the destination Writable stream is not overwhelmed by a faster Readable\nstream.
The following example pipes all of the data from the readable
into a file\nnamed file.txt
:
const readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);\n
\nIt is possible to attach multiple Writable streams to a single Readable stream.
\nThe readable.pipe()
method returns a reference to the destination stream\nmaking it possible to set up chains of piped streams:
const r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n
\nBy default, stream.end()
is called on the destination Writable\nstream when the source Readable stream emits 'end'
, so that the\ndestination is no longer writable. To disable this default behavior, the end
\noption can be passed as false
, causing the destination stream to remain open,\nas illustrated in the following example:
reader.pipe(writer, { end: false });\nreader.on('end', () => {\n writer.end('Goodbye\\n');\n});\n
\nOne important caveat is that if the Readable stream emits an error during\nprocessing, the Writable destination is not closed automatically. If an\nerror occurs, it will be necessary to manually close each stream in order\nto prevent memory leaks.
\nNote: The process.stderr
and process.stdout
Writable streams are\nnever closed until the Node.js process exits, regardless of the specified\noptions.
The readable.read()
method pulls some data out of the internal buffer and\nreturns it. If no data available to be read, null
is returned. By default,\nthe data will be returned as a Buffer
object unless an encoding has been\nspecified using the readable.setEncoding()
method or the stream is operating\nin object mode.
The optional size
argument specifies a specific number of bytes to read. If\nsize
bytes are not available to be read, null
will be returned unless\nthe stream has ended, in which case all of the data remaining in the internal\nbuffer will be returned (even if it exceeds size
bytes).
If the size
argument is not specified, all of the data contained in the\ninternal buffer will be returned.
The readable.read()
method should only be called on Readable streams operating\nin paused mode. In flowing mode, readable.read()
is called automatically until\nthe internal buffer is fully drained.
const readable = getReadableStreamSomehow();\nreadable.on('readable', () => {\n var chunk;\n while (null !== (chunk = readable.read())) {\n console.log(`Received ${chunk.length} bytes of data.`);\n }\n});\n
\nIn general, it is recommended that developers avoid the use of the 'readable'
\nevent and the readable.read()
method in favor of using either\nreadable.pipe()
or the 'data'
event.
A Readable stream in object mode will always return a single item from\na call to readable.read(size)
, regardless of the value of the\nsize
argument.
Note: If the readable.read()
method returns a chunk of data, a 'data'
\nevent will also be emitted.
Note: Calling stream.read([size])
after the 'end'
\nevent has been emitted will return null
. No runtime error will be raised.
The readable.resume()
method causes an explicitly paused Readable stream to\nresume emitting 'data'
events, switching the stream into flowing mode.
The readable.resume()
method can be used to fully consume the data from a\nstream without actually processing any of that data as illustrated in the\nfollowing example:
getReadableStreamSomehow()\n .resume()\n .on('end', () => {\n console.log('Reached the end, but did not read anything.');\n });\n
\n"
},
{
"textRaw": "readable.setEncoding(encoding)",
"type": "method",
"name": "setEncoding",
"meta": {
"added": [
"v0.9.4"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: `this` ",
"name": "return",
"desc": "`this`"
},
"params": [
{
"textRaw": "`encoding` {String} The encoding to use. ",
"name": "encoding",
"type": "String",
"desc": "The encoding to use."
}
]
},
{
"params": [
{
"name": "encoding"
}
]
}
],
"desc": "The readable.setEncoding()
method sets the default character encoding for\ndata read from the Readable stream.
Setting an encoding causes the stream data\nto be returned as string of the specified encoding rather than as Buffer
\nobjects. For instance, calling readable.setEncoding('utf8')
will cause the\noutput data will be interpreted as UTF-8 data, and passed as strings. Calling\nreadable.setEncoding('hex')
will cause the data to be encoded in hexadecimal\nstring format.
The Readable stream will properly handle multi-byte characters delivered through\nthe stream that would otherwise become improperly decoded if simply pulled from\nthe stream as Buffer
objects.
Encoding can be disabled by calling readable.setEncoding(null)
. This approach\nis useful when working with binary data or with large multi-byte strings spread\nout over multiple chunks.
const readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n assert.equal(typeof chunk, 'string');\n console.log('got %d characters of string data', chunk.length);\n});\n
\n"
},
{
"textRaw": "readable.unpipe([destination])",
"type": "method",
"name": "unpipe",
"meta": {
"added": [
"v0.9.4"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`destination` {stream.Writable} Optional specific stream to unpipe ",
"name": "destination",
"type": "stream.Writable",
"desc": "Optional specific stream to unpipe",
"optional": true
}
]
},
{
"params": [
{
"name": "destination",
"optional": true
}
]
}
],
"desc": "The readable.unpipe()
method detaches a Writable stream previously attached\nusing the stream.pipe()
method.
If the destination
is not specified, then all pipes are detached.
If the destination
is specified, but no pipe is set up for it, then\nthe method does nothing.
const readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(() => {\n console.log('Stop writing to file.txt');\n readable.unpipe(writable);\n console.log('Manually close the file stream');\n writable.end();\n}, 1000);\n
\n"
},
{
"textRaw": "readable.unshift(chunk)",
"type": "method",
"name": "unshift",
"meta": {
"added": [
"v0.9.11"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`chunk` {Buffer|String} Chunk of data to unshift onto the read queue ",
"name": "chunk",
"type": "Buffer|String",
"desc": "Chunk of data to unshift onto the read queue"
}
]
},
{
"params": [
{
"name": "chunk"
}
]
}
],
"desc": "The readable.unshift()
method pushes a chunk of data back into the internal\nbuffer. This is useful in certain situations where a stream is being consumed by\ncode that needs to "un-consume" some amount of data that it has optimistically\npulled out of the source, so that the data can be passed on to some other party.
Note: The stream.unshift(chunk)
method cannot be called after the\n'end'
event has been emitted or a runtime error will be thrown.
Developers using stream.unshift()
often should consider switching to\nuse of a Transform stream instead. See the API for Stream Implementers\nsection for more information.
// Pull off a header delimited by \\n\\n\n// use unshift() if we get too much\n// Call the callback with (error, header, stream)\nconst StringDecoder = require('string_decoder').StringDecoder;\nfunction parseHeader(stream, callback) {\n stream.on('error', callback);\n stream.on('readable', onReadable);\n const 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 const remaining = split.join('\\n\\n');\n const buf = Buffer.from(remaining, 'utf8');\n stream.removeListener('error', callback);\n // set the readable listener before unshifting\n stream.removeListener('readable', onReadable);\n if (buf.length)\n stream.unshift(buf);\n // now the body of the message can be read from the stream.\n callback(null, header, stream);\n } else {\n // still reading the header.\n header += str;\n }\n }\n }\n}\n
\nNote: Unlike stream.push(chunk)
, stream.unshift(chunk)
\nwill not end the reading process by resetting the internal reading state of the\nstream. This can cause unexpected results if readable.unshift()
is called\nduring a read (i.e. from within a stream._read()
\nimplementation on a custom stream). Following the call to readable.unshift()
\nwith an immediate stream.push('')
will reset the reading state\nappropriately, however it is best to simply avoid calling readable.unshift()
\nwhile in the process of performing a read.
Versions of Node.js prior to v0.10 had streams that did not implement the\nentire stream
module API as it is currently defined. (See Compatibility\nfor more information.)
When using an older Node.js library that emits 'data'
events and has a\nstream.pause()
method that is advisory only, the\nreadable.wrap()
method can be used to create a Readable stream that uses\nthe old stream as its data source.
It will rarely be necessary to use readable.wrap()
but the method has been\nprovided as a convenience for interacting with older Node.js applications and\nlibraries.
For example:
\nconst OldReader = require('./old-api-module.js').OldReader;\nconst Readable = require('stream').Readable;\nconst oreader = new OldReader;\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n myReader.read(); // etc.\n});\n
\n"
}
]
}
],
"type": "misc",
"displayName": "Readable Streams"
},
{
"textRaw": "Duplex and Transform Streams",
"name": "duplex_and_transform_streams",
"classes": [
{
"textRaw": "Class: stream.Duplex",
"type": "class",
"name": "stream.Duplex",
"meta": {
"added": [
"v0.9.4"
]
},
"desc": "Duplex streams are streams that implement both the Readable and\nWritable interfaces.
\nExamples of Duplex streams include:
\n\n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "meta": { "added": [ "v0.9.4" ] }, "desc": "Transform streams are Duplex streams where the output is in some way\nrelated to the input. Like all Duplex streams, Transform streams\nimplement both the Readable and Writable interfaces.
\nExamples of Transform streams include:
\n\n" } ], "type": "misc", "displayName": "Duplex and Transform Streams" } ] }, { "textRaw": "API for Stream Implementers", "name": "API for Stream Implementers", "type": "misc", "desc": "The stream
module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.
First, a stream developer would declare a new JavaScript class that extends one\nof the four basic stream classes (stream.Writable
, stream.Readable
,\nstream.Duplex
, or stream.Transform
), making sure the call the appropriate\nparent class constructor:
const Writable = require('stream').Writable;\n\nclass MyWritable extends Writable {\n constructor(options) {\n super(options);\n }\n}\n
\nThe new stream class must then implement one or more specific methods, depending\non the type of stream being created, as detailed in the chart below:
\n\n Use-case \n | \n \n Class \n | \n \n Method(s) to implement \n | \n
---|---|---|
\n Reading only \n | \n \n \n | \n\n \n | \n
\n Writing only \n | \n \n \n | \n\n \n | \n
\n Reading and writing \n | \n \n \n | \n\n \n | \n
\n Operate on written data, then read the result \n | \n \n \n | \n\n \n | \n
Note: The implementation code for a stream should never call the "public"\nmethods of a stream that are intended for use by consumers (as described in\nthe API for Stream Consumers section). Doing so may lead to adverse\nside effects in application code consuming the stream.
\n", "miscs": [ { "textRaw": "Simplified Construction", "name": "simplified_construction", "desc": "For many simple cases, it is possible to construct a stream without relying on\ninheritance. This can be accomplished by directly creating instances of the\nstream.Writable
, stream.Readable
, stream.Duplex
or stream.Transform
\nobjects and passing appropriate methods as constructor options.
For example:
\nconst Writable = require('stream').Writable;\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n // ...\n }\n});\n
\n",
"type": "misc",
"displayName": "Simplified Construction"
},
{
"textRaw": "Implementing a Writable Stream",
"name": "implementing_a_writable_stream",
"desc": "The stream.Writable
class is extended to implement a Writable stream.
Custom Writable streams must call the new stream.Writable([options])
\nconstructor and implement the writable._write()
method. The\nwritable._writev()
method may also be implemented.
For example:
\nconst Writable = require('stream').Writable;\n\nclass MyWritable extends Writable {\n constructor(options) {\n // Calls the stream.Writable() constructor\n super(options);\n }\n}\n
\nOr, when using pre-ES6 style constructors:
\nconst Writable = require('stream').Writable;\nconst util = require('util');\n\nfunction MyWritable(options) {\n if (!(this instanceof MyWritable))\n return new MyWritable(options);\n Writable.call(this, options);\n}\nutil.inherits(MyWritable, Writable);\n
\nOr, using the Simplified Constructor approach:
\nconst Writable = require('stream').Writable;\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n // ...\n },\n writev(chunks, callback) {\n // ...\n }\n});\n
\n"
},
{
"textRaw": "writable.\\_write(chunk, encoding, callback)",
"type": "method",
"name": "\\_write",
"signatures": [
{
"params": [
{
"textRaw": "`chunk` {Buffer|String} The chunk to be written. Will **always** be a buffer unless the `decodeStrings` option was set to `false`. ",
"name": "chunk",
"type": "Buffer|String",
"desc": "The chunk to be written. Will **always** be a buffer unless the `decodeStrings` option was set to `false`."
},
{
"textRaw": "`encoding` {String} If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored. ",
"name": "encoding",
"type": "String",
"desc": "If the chunk is a string, then `encoding` is the character encoding of that string. If chunk is a `Buffer`, or if the stream is operating in object mode, `encoding` may be ignored."
},
{
"textRaw": "`callback` {Function} Call this function (optionally with an error argument) when processing is complete for the supplied chunk. ",
"name": "callback",
"type": "Function",
"desc": "Call this function (optionally with an error argument) when processing is complete for the supplied chunk."
}
]
},
{
"params": [
{
"name": "chunk"
},
{
"name": "encoding"
},
{
"name": "callback"
}
]
}
],
"desc": "All Writable stream implementations must provide a\nwritable._write()
method to send data to the underlying\nresource.
Note: Transform streams provide their own implementation of the\nwritable._write()
.
Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Writable\nclass methods only.
\nThe callback
method must be called to signal either that the write completed\nsuccessfully or failed with an error. The first argument passed to the\ncallback
must be the Error
object if the call failed or null
if the\nwrite succeeded.
It is important to note that all calls to writable.write()
that occur between\nthe time writable._write()
is called and the callback
is called will cause\nthe written data to be buffered. Once the callback
is invoked, the stream will\nemit a 'drain'
event. If a stream implementation is capable of processing\nmultiple chunks of data at once, the writable._writev()
method should be\nimplemented.
If the decodeStrings
property is set in the constructor options, then\nchunk
may be a string rather than a Buffer, and encoding
will\nindicate the character encoding of the string. This is to support\nimplementations that have an optimized handling for certain string\ndata encodings. If the decodeStrings
property is explicitly set to false
,\nthe encoding
argument can be safely ignored, and chunk
will remain the same\nobject that is passed to .write()
.
The writable._write()
method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Writable\nclass methods only.
\nThe writable._writev()
method may be implemented in addition to\nwritable._write()
in stream implementations that are capable of processing\nmultiple chunks of data at once. If implemented, the method will be called with\nall chunks of data currently buffered in the write queue.
The writable._writev()
method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
It is recommended that errors occurring during the processing of the\nwritable._write()
and writable._writev()
methods are reported by invoking\nthe callback and passing the error as the first argument. This will cause an\n'error'
event to be emitted by the Writable. Throwing an Error from within\nwritable._write()
can result in unexpected and inconsistent behavior depending\non how the stream is being used. Using the callback ensures consistent and\npredictable handling of errors.
const Writable = require('stream').Writable;\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n if (chunk.toString().indexOf('a') >= 0) {\n callback(new Error('chunk is invalid'));\n } else {\n callback();\n }\n }\n});\n
\n",
"type": "module",
"displayName": "Errors While Writing"
},
{
"textRaw": "An Example Writable Stream",
"name": "an_example_writable_stream",
"desc": "The following illustrates a rather simplistic (and somewhat pointless) custom\nWritable stream implementation. While this specific Writable stream instance\nis not of any real particular usefulness, the example illustrates each of the\nrequired elements of a custom Writable stream instance:
\nconst Writable = require('stream').Writable;\n\nclass MyWritable extends Writable {\n constructor(options) {\n super(options);\n }\n\n _write(chunk, encoding, callback) {\n if (chunk.toString().indexOf('a') >= 0) {\n callback(new Error('chunk is invalid'));\n } else {\n callback();\n }\n }\n}\n
\n",
"type": "module",
"displayName": "An Example Writable Stream"
}
],
"type": "misc",
"displayName": "Implementing a Writable Stream"
},
{
"textRaw": "Implementing a Readable Stream",
"name": "implementing_a_readable_stream",
"desc": "The stream.Readable
class is extended to implement a Readable stream.
Custom Readable streams must call the new stream.Readable([options])
\nconstructor and implement the readable._read()
method.
For example:
\nconst Readable = require('stream').Readable;\n\nclass MyReadable extends Readable {\n constructor(options) {\n // Calls the stream.Readable(options) constructor\n super(options);\n }\n}\n
\nOr, when using pre-ES6 style constructors:
\nconst Readable = require('stream').Readable;\nconst util = require('util');\n\nfunction MyReadable(options) {\n if (!(this instanceof MyReadable))\n return new MyReadable(options);\n Readable.call(this, options);\n}\nutil.inherits(MyReadable, Readable);\n
\nOr, using the Simplified Constructor approach:
\nconst Readable = require('stream').Readable;\n\nconst myReadable = new Readable({\n read(size) {\n // ...\n }\n});\n
\n"
},
{
"textRaw": "readable.\\_read(size)",
"type": "method",
"name": "\\_read",
"signatures": [
{
"params": [
{
"textRaw": "`size` {Number} Number of bytes to read asynchronously ",
"name": "size",
"type": "Number",
"desc": "Number of bytes to read asynchronously"
}
]
},
{
"params": [
{
"name": "size"
}
]
}
],
"desc": "Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Readable\nclass methods only.
\nAll Readable stream implementations must provide an implementation of the\nreadable._read()
method to fetch data from the underlying resource.
When readable._read()
is called, if data is available from the resource, the\nimplementation should begin pushing that data into the read queue using the\nthis.push(dataChunk)
method. _read()
should continue reading\nfrom the resource and pushing data until readable.push()
returns false
. Only\nwhen _read()
is called again after it has stopped should it resume pushing\nadditional data onto the queue.
Note: Once the readable._read()
method has been called, it will not be\ncalled again until the readable.push()
method is called.
The size
argument is advisory. For implementations where a "read" is a\nsingle operation that returns data can use the size
argument to determine how\nmuch data to fetch. Other implementations may ignore this argument and simply\nprovide data whenever it becomes available. There is no need to "wait" until\nsize
bytes are available before calling stream.push(chunk)
.
The readable._read()
method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
When chunk
is a Buffer
or string
, the chunk
of data will be added to the\ninternal queue for users of the stream to consume. Passing chunk
as null
\nsignals the end of the stream (EOF), after which no more data can be written.
When the Readable is operating in paused mode, the data added with\nreadable.push()
can be read out by calling the\nreadable.read()
method when the 'readable'
event is\nemitted.
When the Readable is operating in flowing mode, the data added with\nreadable.push()
will be delivered by emitting a 'data'
event.
The readable.push()
method is designed to be as flexible as possible. For\nexample, when wrapping a lower-level source that provides some form of\npause/resume mechanism, and a data callback, the low-level source can be wrapped\nby the custom Readable instance as illustrated in the following example:
// source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nclass SourceWrapper extends Readable {\n constructor(options) {\n super(options);\n\n this._source = getLowlevelSourceObject();\n\n // Every time there's data, push it into the internal buffer.\n this._source.ondata = (chunk) => {\n // if push() returns false, then stop reading from source\n if (!this.push(chunk))\n this._source.readStop();\n };\n\n // When the source ends, push the EOF-signaling `null` chunk\n this._source.onend = () => {\n this.push(null);\n };\n }\n // _read will be called when the stream wants to pull more data in\n // the advisory size argument is ignored in this case.\n _read(size) {\n this._source.readStart();\n }\n}\n
\nNote: The readable.push()
method is intended be called only by Readable\nImplementers, and only from within the readable._read()
method.
It is recommended that errors occurring during the processing of the\nreadable._read()
method are emitted using the 'error'
event rather than\nbeing thrown. Throwing an Error from within readable._read()
can result in\nunexpected and inconsistent behavior depending on whether the stream is\noperating in flowing or paused mode. Using the 'error'
event ensures\nconsistent and predictable handling of errors.
const Readable = require('stream').Readable;\n\nconst myReadable = new Readable({\n read(size) {\n if (checkSomeErrorCondition()) {\n process.nextTick(() => this.emit('error', err));\n return;\n }\n // do some work\n }\n});\n
\n",
"type": "module",
"displayName": "Errors While Reading"
}
],
"examples": [
{
"textRaw": "An Example Counting Stream",
"name": "An Example Counting Stream",
"type": "example",
"desc": "The following is a basic example of a Readable stream that emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.
\nconst Readable = require('stream').Readable;\n\nclass Counter extends Readable {\n constructor(opt) {\n super(opt);\n this._max = 1000000;\n this._index = 1;\n }\n\n _read() {\n var i = this._index++;\n if (i > this._max)\n this.push(null);\n else {\n var str = '' + i;\n var buf = Buffer.from(str, 'ascii');\n this.push(buf);\n }\n }\n}\n
\n"
}
],
"type": "misc",
"displayName": "Implementing a Readable Stream"
},
{
"textRaw": "Implementing a Duplex Stream",
"name": "implementing_a_duplex_stream",
"desc": "A Duplex stream is one that implements both Readable and Writable,\nsuch as a TCP socket connection.
\nBecause JavaScript does not have support for multiple inheritance, the\nstream.Duplex
class is extended to implement a Duplex stream (as opposed\nto extending the stream.Readable
and stream.Writable
classes).
Note: The stream.Duplex
class prototypically inherits from stream.Readable
\nand parasitically from stream.Writable
, but instanceof
will work properly\nfor both base classes due to overriding Symbol.hasInstance
\non stream.Writable
.
Custom Duplex streams must call the new stream.Duplex([options])
\nconstructor and implement both the readable._read()
and\nwritable._write()
methods.
For example:
\nconst Duplex = require('stream').Duplex;\n\nclass MyDuplex extends Duplex {\n constructor(options) {\n super(options);\n }\n}\n
\nOr, when using pre-ES6 style constructors:
\nconst Duplex = require('stream').Duplex;\nconst util = require('util');\n\nfunction MyDuplex(options) {\n if (!(this instanceof MyDuplex))\n return new MyDuplex(options);\n Duplex.call(this, options);\n}\nutil.inherits(MyDuplex, Duplex);\n
\nOr, using the Simplified Constructor approach:
\nconst Duplex = require('stream').Duplex;\n\nconst myDuplex = new Duplex({\n read(size) {\n // ...\n },\n write(chunk, encoding, callback) {\n // ...\n }\n});\n
\n"
}
],
"modules": [
{
"textRaw": "An Example Duplex Stream",
"name": "an_example_duplex_stream",
"desc": "The following illustrates a simple example of a Duplex stream that wraps a\nhypothetical lower-level source object to which data can be written, and\nfrom which data can be read, albeit using an API that is not compatible with\nNode.js streams.\nThe following illustrates a simple example of a Duplex stream that buffers\nincoming written data via the Writable interface that is read back out\nvia the Readable interface.
\nconst Duplex = require('stream').Duplex;\nconst kSource = Symbol('source');\n\nclass MyDuplex extends Duplex {\n constructor(source, options) {\n super(options);\n this[kSource] = source;\n }\n\n _write(chunk, encoding, callback) {\n // The underlying source only deals with strings\n if (Buffer.isBuffer(chunk))\n chunk = chunk.toString();\n this[kSource].writeSomeData(chunk);\n callback();\n }\n\n _read(size) {\n this[kSource].fetchSomeData(size, (data, encoding) => {\n this.push(Buffer.from(data, encoding));\n });\n }\n}\n
\nThe most important aspect of a Duplex stream is that the Readable and Writable\nsides operate independently of one another despite co-existing within a single\nobject instance.
\n", "type": "module", "displayName": "An Example Duplex Stream" }, { "textRaw": "Object Mode Duplex Streams", "name": "object_mode_duplex_streams", "desc": "For Duplex streams, objectMode
can be set exclusively for either the Readable\nor Writable side using the readableObjectMode
and writableObjectMode
options\nrespectively.
In the following example, for instance, a new Transform stream (which is a\ntype of Duplex stream) is created that has an object mode Writable side\nthat accepts JavaScript numbers that are converted to hexadecimal strings on\nthe Readable side.
\nconst Transform = require('stream').Transform;\n\n// All Transform streams are also Duplex Streams\nconst myTransform = new Transform({\n writableObjectMode: true,\n\n transform(chunk, encoding, callback) {\n // Coerce the chunk to a number if necessary\n chunk |= 0;\n\n // Transform the chunk into something else.\n const data = chunk.toString(16);\n\n // Push the data onto the readable queue.\n callback(null, '0'.repeat(data.length % 2) + data);\n }\n});\n\nmyTransform.setEncoding('ascii');\nmyTransform.on('data', (chunk) => console.log(chunk));\n\nmyTransform.write(1);\n// Prints: 01\nmyTransform.write(10);\n// Prints: 0a\nmyTransform.write(100);\n// Prints: 64\n
\n",
"type": "module",
"displayName": "Object Mode Duplex Streams"
}
],
"type": "misc",
"displayName": "Implementing a Duplex Stream"
},
{
"textRaw": "Implementing a Transform Stream",
"name": "implementing_a_transform_stream",
"desc": "A Transform stream is a Duplex stream where the output is computed\nin some way from the input. Examples include zlib streams or crypto\nstreams that compress, encrypt, or decrypt data.
\nNote: 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.
The stream.Transform
class is extended to implement a Transform stream.
The stream.Transform
class prototypically inherits from stream.Duplex
and\nimplements its own versions of the writable._write()
and readable._read()
\nmethods. Custom Transform implementations must implement the\ntransform._transform()
method and may also implement\nthe transform._flush()
method.
Note: Care must be taken when using Transform streams in that data written\nto the stream can cause the Writable side of the stream to become paused if\nthe output on the Readable side is not consumed.
\n", "methods": [ { "textRaw": "new stream.Transform([options])", "type": "method", "name": "Transform", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both Writable and Readable constructors. Also has the following fields: ", "options": [ { "textRaw": "`transform` {Function} Implementation for the [`stream._transform()`][stream-_transform] method. ", "name": "transform", "type": "Function", "desc": "Implementation for the [`stream._transform()`][stream-_transform] method." }, { "textRaw": "`flush` {Function} Implementation for the [`stream._flush()`][stream-_flush] method. ", "name": "flush", "type": "Function", "desc": "Implementation for the [`stream._flush()`][stream-_flush] method." } ], "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors. Also has the following fields:", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "For example:
\nconst Transform = require('stream').Transform;\n\nclass MyTransform extends Transform {\n constructor(options) {\n super(options);\n }\n}\n
\nOr, when using pre-ES6 style constructors:
\nconst Transform = require('stream').Transform;\nconst util = require('util');\n\nfunction MyTransform(options) {\n if (!(this instanceof MyTransform))\n return new MyTransform(options);\n Transform.call(this, options);\n}\nutil.inherits(MyTransform, Transform);\n
\nOr, using the Simplified Constructor approach:
\nconst Transform = require('stream').Transform;\n\nconst myTransform = new Transform({\n transform(chunk, encoding, callback) {\n // ...\n }\n});\n
\n"
},
{
"textRaw": "transform.\\_flush(callback)",
"type": "method",
"name": "\\_flush",
"signatures": [
{
"params": [
{
"textRaw": "`callback` {Function} A callback function (optionally with an error argument and data) to be called when remaining data has been flushed. ",
"name": "callback",
"type": "Function",
"desc": "A callback function (optionally with an error argument and data) to be called when remaining data has been flushed."
}
]
},
{
"params": [
{
"name": "callback"
}
]
}
],
"desc": "Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Readable\nclass methods only.
\nIn some cases, a transform operation may need to emit an additional bit of\ndata at the end of the stream. For example, a zlib
compression stream will\nstore an amount of internal state used to optimally compress the output. When\nthe stream ends, however, that additional data needs to be flushed so that the\ncompressed data will be complete.
Custom Transform implementations may implement the transform._flush()
\nmethod. This will be called when there is no more written data to be consumed,\nbut before the 'end'
event is emitted signaling the end of the\nReadable stream.
Within the transform._flush()
implementation, the readable.push()
method\nmay be called zero or more times, as appropriate. The callback
function must\nbe called when the flush operation is complete.
The transform._flush()
method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
Note: This function MUST NOT be called by application code directly. It\nshould be implemented by child classes, and called only by the internal Readable\nclass methods only.
\nAll Transform stream implementations must provide a _transform()
\nmethod to accept input and produce output. The transform._transform()
\nimplementation handles the bytes being written, computes an output, then passes\nthat output off to the readable portion using the readable.push()
method.
The transform.push()
method may be called zero or more times to generate\noutput from a single input chunk, depending on how much is to be output\nas a result of the chunk.
It is possible that no output is generated from any given chunk of input data.
\nThe callback
function must be called only when the current chunk is completely\nconsumed. The first argument passed to the callback
must be an Error
object\nif an error occurred while processing the input or null
otherwise. If a second\nargument is passed to the callback
, it will be forwarded on to the\nreadable.push()
method. In other words the following are equivalent:
transform.prototype._transform = function (data, encoding, callback) {\n this.push(data);\n callback();\n};\n\ntransform.prototype._transform = function (data, encoding, callback) {\n callback(null, data);\n};\n
\nThe transform._transform()
method is prefixed with an underscore because it\nis internal to the class that defines it, and should never be called directly by\nuser programs.
The 'finish'
and 'end'
events are from the stream.Writable
\nand stream.Readable
classes, respectively. The 'finish'
event is emitted\nafter stream.end()
is called and all chunks have been processed\nby stream._transform()
. The 'end'
event is emitted\nafter all data has been output, which occurs after the callback in\ntransform._flush()
has been called.
The stream.PassThrough
class is a trivial implementation of a Transform\nstream that simply passes the input bytes across to the output. Its purpose is\nprimarily for examples and testing, but there are some use cases where\nstream.PassThrough
is useful as a building block for novel sorts of streams.
In versions of Node.js prior to v0.10, the Readable stream interface was\nsimpler, but also less powerful and less useful.
\nstream.read()
method,\n'data'
events would begin emitting immediately. Applications that\nwould need to perform some amount of work to decide how to handle data\nwere required to store read data into buffers so the data would not be lost.stream.pause()
method was advisory, rather than\nguaranteed. This meant that it was still necessary to be prepared to receive\n'data'
events even when the stream was in a paused state.In Node.js v0.10, the Readable class was added. For backwards compatibility\nwith older Node.js programs, Readable streams switch into "flowing mode" when a\n'data'
event handler is added, or when the\nstream.resume()
method is called. The effect is that, even\nwhen not using the new stream.read()
method and\n'readable'
event, it is no longer necessary to worry about losing\n'data'
chunks.
While most applications will continue to function normally, this introduces an\nedge case in the following conditions:
\n'data'
event listener is added.stream.resume()
method is never called.For example, consider the following code:
\n// WARNING! BROKEN!\nnet.createServer((socket) => {\n\n // we add an 'end' method, but never consume the data\n socket.on('end', () => {\n // It will never get here.\n socket.end('The message was received but was not processed.\\n');\n });\n\n}).listen(1337);\n
\nIn versions of Node.js prior to v0.10, the incoming message data would be\nsimply discarded. However, in Node.js v0.10 and beyond, the socket remains\npaused forever.
\nThe workaround in this situation is to call the\nstream.resume()
method to begin the flow of data:
// Workaround\nnet.createServer((socket) => {\n\n socket.on('end', () => {\n socket.end('The message was received but was not processed.\\n');\n });\n\n // start the flow of data, discarding it.\n socket.resume();\n\n}).listen(1337);\n
\nIn addition to new Readable streams switching into flowing mode,\npre-v0.10 style streams can be wrapped in a Readable class using the\nreadable.wrap()
method.
There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0)
, which will\nalways return null
.
If the internal read buffer is below the highWaterMark
, and the\nstream is not currently reading, then calling stream.read(0)
will trigger\na low-level stream._read()
call.
While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.
\n", "type": "misc", "displayName": "`readable.read(0)`" }, { "textRaw": "`readable.push('')`", "name": "`readable.push('')`", "desc": "Use of readable.push('')
is not recommended.
Pushing a zero-byte string or Buffer
to a stream that is not in object mode\nhas an interesting side effect. Because it is a call to\nreadable.push()
, the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.
The string_decoder
module provides an API for decoding Buffer
objects into\nstrings in a manner that preserves encoded multi-byte UTF-8 and UTF-16\ncharacters. It can be accessed using:
const StringDecoder = require('string_decoder').StringDecoder;\n
\nThe following example shows the basic use of the StringDecoder
class.
const StringDecoder = require('string_decoder').StringDecoder;\nconst decoder = new StringDecoder('utf8');\n\nconst cent = Buffer.from([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nconst euro = Buffer.from([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));\n
\nWhen a Buffer
instance is written to the StringDecoder
instance, an\ninternal buffer is used to ensure that the decoded string does not contain\nany incomplete multibyte characters. These are held in the buffer until the\nnext call to stringDecoder.write()
or until stringDecoder.end()
is called.
In the following example, the three UTF-8 encoded bytes of the European Euro\nsymbol (€
) are written over three separate operations:
const StringDecoder = require('string_decoder').StringDecoder;\nconst decoder = new StringDecoder('utf8');\n\ndecoder.write(Buffer.from([0xE2]));\ndecoder.write(Buffer.from([0x82]));\nconsole.log(decoder.end(Buffer.from([0xAC])));\n
\n",
"classes": [
{
"textRaw": "Class: new StringDecoder([encoding])",
"type": "class",
"name": "new",
"meta": {
"added": [
"v0.1.99"
]
},
"desc": "encoding
{string} The character encoding the StringDecoder
will use.\nDefaults to 'utf8'
.Creates a new StringDecoder
instance.
Returns any remaining input stored in the internal buffer as a string. Bytes\nrepresenting incomplete UTF-8 and UTF-16 characters will be replaced with\nsubstitution characters appropriate for the character encoding.
\nIf the buffer
argument is provided, one final call to stringDecoder.write()
\nis performed before returning the remaining input.
Returns a decoded string, ensuring that any incomplete multibyte characters at\nthe end of the Buffer
are omitted from the returned string and stored in an\ninternal buffer for the next call to stringDecoder.write()
or\nstringDecoder.end()
.
The timer
module exposes a global API for scheduling functions to\nbe called at some future period of time. Because the timer functions are\nglobals, there is no need to call require('timers')
to use the API.
The timer functions within Node.js implement a similar API as the timers API\nprovided by Web Browsers but use a different internal implementation that is\nbuilt around the Node.js Event Loop.
\n", "classes": [ { "textRaw": "Class: Immediate", "type": "class", "name": "Immediate", "desc": "This object is created internally and is returned from setImmediate()
. It\ncan be passed to clearImmediate()
in order to cancel the scheduled\nactions.
This object is created internally and is returned from setTimeout()
and\nsetInterval()
. It can be passed to clearTimeout()
or\nclearInterval()
(respectively) in order to cancel the scheduled actions.
By default, when a timer is scheduled using either setTimeout()
or\nsetInterval()
, the Node.js event loop will continue running as long as the\ntimer is active. Each of the Timeout
objects returned by these functions\nexport both timeout.ref()
and timeout.unref()
functions that can be used to\ncontrol this default behavior.
When called, requests that the Node.js event loop not exit so long as the\nTimeout
is active. Calling timeout.ref()
multiple times will have no effect.
Note: By default, all Timeout
objects are "ref'd", making it normally\nunnecessary to call timeout.ref()
unless timeout.unref()
had been called\npreviously.
Returns a reference to the Timeout
.
When called, the active Timeout
object will not require the Node.js event loop\nto remain active. If there is no other activity keeping the event loop running,\nthe process may exit before the Timeout
object's callback is invoked. Calling\ntimeout.unref()
multiple times will have no effect.
Note: Calling timeout.unref()
creates an internal timer that will wake the\nNode.js event loop. Creating too many of these can adversely impact performance\nof the Node.js application.
Returns a reference to the Timeout
.
A timer in Node.js is an internal construct that calls a given function after\na certain period of time. When a timer's function is called varies depending on\nwhich method was used to create the timer and what other work the Node.js\nevent loop is doing.
\n", "methods": [ { "textRaw": "setImmediate(callback[, ...args])", "type": "method", "name": "setImmediate", "meta": { "added": [ "v0.9.1" ] }, "signatures": [ { "params": [ { "textRaw": "`callback` {Function} The function to call at the end of this turn of [the Node.js Event Loop] ", "name": "callback", "type": "Function", "desc": "The function to call at the end of this turn of [the Node.js Event Loop]" }, { "textRaw": "`...args` {any} Optional arguments to pass when the `callback` is called. ", "name": "...args", "type": "any", "desc": "Optional arguments to pass when the `callback` is called.", "optional": true } ] }, { "params": [ { "name": "callback" }, { "name": "...args", "optional": true } ] } ], "desc": "Schedules the "immediate" execution of the callback
after I/O events'\ncallbacks and before timers created using setTimeout()
and\nsetInterval()
are triggered. Returns an Immediate
for use with\nclearImmediate()
.
When multiple calls to setImmediate()
are made, the callback
functions are\nqueued for execution in the order in which they are created. The entire callback\nqueue is processed every event loop iteration. If an immediate timer is queued\nfrom inside an executing callback, that timer will not be triggered until the\nnext event loop iteration.
If callback
is not a function, a TypeError
will be thrown.
Schedules repeated execution of callback
every delay
milliseconds.\nReturns a Timeout
for use with clearInterval()
.
When delay
is larger than 2147483647
or less than 1
, the delay
will be\nset to 1
.
If callback
is not a function, a TypeError
will be thrown.
Schedules execution of a one-time callback
after delay
milliseconds.\nReturns a Timeout
for use with clearTimeout()
.
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.
Note: When delay
is larger than 2147483647
or less than 1
, the delay
\nwill be set to 1
.
If callback
is not a function, a TypeError
will be thrown.
The setImmediate()
, setInterval()
, and setTimeout()
methods\neach return objects that represent the scheduled timers. These can be used to\ncancel the timer and prevent it from triggering.
Cancels an Immediate
object created by setImmediate()
.
Cancels a Timeout
object created by setInterval()
.
Cancels a Timeout
object created by setTimeout()
.
The tls
module provides an implementation of the Transport Layer Security\n(TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL.\nThe module can be accessed using:
const tls = require('tls');\n
\n",
"modules": [
{
"textRaw": "TLS/SSL Concepts",
"name": "tls/ssl_concepts",
"desc": "The TLS/SSL is a public/private key infrastructure (PKI). For most common\ncases, each client and server must have a private key.
\nPrivate keys can be generated in multiple ways. The example below illustrates\nuse of the OpenSSL command-line interface to generate a 2048-bit RSA private\nkey:
\nopenssl genrsa -out ryans-key.pem 2048\n
\nWith TLS/SSL, all servers (and some clients) must have a certificate.\nCertificates are public keys that correspond to a private key, and that are\ndigitally signed either by a Certificate Authority or by the owner of the\nprivate key (such certificates are referred to as "self-signed"). The first\nstep to obtaining a certificate is to create a Certificate Signing Request\n(CSR) file.
\nThe OpenSSL command-line interface can be used to generate a CSR for a private\nkey:
\nopenssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem\n
\nOnce the CSR file is generated, it can either be sent to a Certificate\nAuthority for signing or used to generate a self-signed certificate.
\nCreating a self-signed certificate using the OpenSSL command-line interface\nis illustrated in the example below:
\nopenssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem\n
\nOnce the certificate is generated, it can be used to generate a .pfx
or\n.p12
file:
openssl pkcs12 -export -in ryans-cert.pem -inkey ryans-key.pem \\\n -certfile ca-cert.pem -out ryans.pfx\n
\nWhere:
\nin
: is the signed certificateinkey
: is the associated private keycertfile
: is a concatenation of all Certificate Authority (CA) certs into\n a single file, e.g. cat ca1-cert.pem ca2-cert.pem > ca-cert.pem
The term "Forward Secrecy" or "Perfect Forward Secrecy" describes a feature of\nkey-agreement (i.e., key-exchange) methods. That is, the server and client keys\nare used to negotiate new temporary keys that are used specifically and only for\nthe current communication session. Practically, this means that even if the\nserver's private key is compromised, communication can only be decrypted by\neavesdroppers if the attacker manages to obtain the key-pair specifically\ngenerated for the session.
\nPerfect Forward Secrecy is achieved by randomly generating a key pair for\nkey-agreement on every TLS/SSL handshake (in contrast to using the same key for\nall sessions). Methods implementing this technique are called "ephemeral".
\nCurrently two methods are commonly used to achieve Perfect Forward Secrecy (note\nthe character "E" appended to the traditional abbreviations):
\nEphemeral methods may have some performance drawbacks, because key generation\nis expensive.
\nTo use Perfect Forward Secrecy using DHE
with the tls
module, it is required\nto generate Diffie-Hellman parameters and specify them with the dhparam
\noption to tls.createSecureContext()
. The following illustrates the use of\nthe OpenSSL command-line interface to generate such parameters:
openssl dhparam -outform PEM -out dhparam.pem 2048\n
\nIf using Perfect Forward Secrecy using ECDHE
, Diffie-Hellman parameters are\nnot required and a default ECDHE curve will be used. The ecdhCurve
property\ncan be used when creating a TLS Server to specify the name of an alternative\ncurve to use, see tls.createServer()
for more info.
ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next\nProtocol Negotiation) and, SNI (Server Name Indication) are TLS\nhandshake extensions:
\nNote: Use of ALPN is recommended over NPN. The NPN extension has never been\nformally defined or documented and generally not recommended for use.
\n" }, { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "The TLS protocol allows clients to renegotiate certain aspects of the TLS\nsession. Unfortunately, session renegotiation requires a disproportionate amount\nof server-side resources, making it a potential vector for denial-of-service\nattacks.
\nTo mitigate the risk, renegotiation is limited to three times every ten minutes.\nAn 'error'
event is emitted on the tls.TLSSocket
instance when this\nthreshold is exceeded. The limits are configurable:
tls.CLIENT_RENEG_LIMIT
{number} Specifies the number of renegotiation\nrequests. Defaults to 3
.tls.CLIENT_RENEG_WINDOW
{number} Specifies the time renegotiation window\nin seconds. Defaults to 600
(10 minutes).Note: The default renegotiation limits should not be modified without a full\nunderstanding of the implications and risks.
\nTo test the renegotiation limits on a server, connect to it using the OpenSSL\ncommand-line client (openssl s_client -connect address:port
) then input\nR<CR>
(i.e., the letter R
followed by a carriage return) multiple times.
Node.js is built with a default suite of enabled and disabled TLS ciphers.\nCurrently, the default cipher suite is:
\nECDHE-RSA-AES128-GCM-SHA256:\nECDHE-ECDSA-AES128-GCM-SHA256:\nECDHE-RSA-AES256-GCM-SHA384:\nECDHE-ECDSA-AES256-GCM-SHA384:\nDHE-RSA-AES128-GCM-SHA256:\nECDHE-RSA-AES128-SHA256:\nDHE-RSA-AES128-SHA256:\nECDHE-RSA-AES256-SHA384:\nDHE-RSA-AES256-SHA384:\nECDHE-RSA-AES256-SHA256:\nDHE-RSA-AES256-SHA256:\nHIGH:\n!aNULL:\n!eNULL:\n!EXPORT:\n!DES:\n!RC4:\n!MD5:\n!PSK:\n!SRP:\n!CAMELLIA\n
\nThis default can be replaced entirely using the --tls-cipher-list
command\nline switch. For instance, the following makes\nECDHE-RSA-AES128-GCM-SHA256:!RC4
the default TLS cipher suite:
node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"\n
\nThe default can also be replaced on a per client or server basis using the\nciphers
option from tls.createSecureContext()
, which is also available\nin tls.createServer()
, tls.connect()
, and when creating new\ntls.TLSSocket
s.
Consult OpenSSL cipher list format documentation for details on the format.
\nNote: The default cipher suite included within Node.js has been carefully\nselected to reflect current security best practices and risk mitigation.\nChanging the default cipher suite can have a significant impact on the security\nof an application. The --tls-cipher-list
switch and ciphers
option should by\nused only if absolutely necessary.
The default cipher suite prefers GCM ciphers for Chrome's 'modern\ncryptography' setting and also prefers ECDHE and DHE ciphers for Perfect\nForward Secrecy, while offering some backward compatibility.
\n128 bit AES is preferred over 192 and 256 bit AES in light of specific\nattacks affecting larger AES key sizes.
\nOld clients that rely on insecure and deprecated RC4 or DES-based ciphers\n(like Internet Explorer 6) cannot complete the handshaking process with\nthe default configuration. If these clients must be supported, the\nTLS recommendations may offer a compatible cipher suite. For more details\non the format, see the OpenSSL cipher list format documentation.
\n", "type": "module", "displayName": "Modifying the Default TLS Cipher suite" }, { "textRaw": "Deprecated APIs", "name": "deprecated_apis", "classes": [ { "textRaw": "Class: CryptoStream", "type": "class", "name": "CryptoStream", "meta": { "added": [ "v0.3.4" ], "deprecated": [ "v0.11.3" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.TLSSocket`][] instead.", "desc": "The tls.CryptoStream
class represents a stream of encrypted data. This class\nhas been deprecated and should no longer be used.
The cryptoStream.bytesWritten
property returns the total number of bytes\nwritten to the underlying socket including the bytes required for the\nimplementation of the TLS protocol.
Returned by tls.createSecurePair()
.
The 'secure'
event is emitted by the SecurePair
object once a secure\nconnection has been established.
As with checking for the server secureConnection
\nevent, pair.cleartext.authorized
should be inspected to confirm whether the\ncertificate used is properly authorized.
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.
\ntls.createSecurePair()
returns a tls.SecurePair
object with cleartext
and\nencrypted
stream properties.
Note: cleartext
has the same API as tls.TLSSocket
.
Note: The tls.createSecurePair()
method is now deprecated in favor of\ntls.TLSSocket()
. For example, the code:
pair = tls.createSecurePair( ... );\npair.encrypted.pipe(socket);\nsocket.pipe(pair.encrypted);\n
\ncan be replaced by:
\nsecure_socket = tls.TLSSocket(socket, options);\n
\nwhere secure_socket
has the same API as pair.cleartext
.
The tls.Server
class is a subclass of net.Server
that accepts encrypted\nconnections using TLS or SSL.
The 'tlsClientError'
event is emitted when an error occurs before a secure\nconnection is established. The listener callback is passed two arguments when\ncalled:
exception
{Error} The Error
object describing the errortlsSocket
{tls.TLSSocket} The tls.TLSSocket
instance from which the\nerror originated.The 'newSession'
event is emitted upon creation of a new TLS session. This may\nbe used to store sessions in external storage. The listener callback is passed\nthree arguments when called:
sessionId
- The TLS session identifiersessionData
- The TLS session datacallback
{Function} A callback function taking no arguments that must be\ninvoked in order for data to be sent or received over the secure connection.Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.
\n", "params": [] }, { "textRaw": "Event: 'OCSPRequest'", "type": "event", "name": "OCSPRequest", "meta": { "added": [ "v0.11.13" ] }, "desc": "The 'OCSPRequest'
event is emitted when the client sends a certificate status\nrequest. The listener callback is passed three arguments when called:
certificate
{Buffer} The server certificateissuer
{Buffer} The issuer's certificatecallback
{Function} A callback function that must be invoked to provide\nthe results of the OCSP request.The server's current certificate can be parsed to obtain the OCSP URL\nand certificate ID; after obtaining an OCSP response, callback(null, resp)
is\nthen invoked, where resp
is a Buffer
instance containing the OCSP response.\nBoth certificate
and issuer
are Buffer
DER-representations of the\nprimary and issuer's certificates. These can be used to obtain the OCSP\ncertificate ID and OCSP endpoint URL.
Alternatively, callback(null, null)
may be called, indicating that there was\nno OCSP response.
Calling callback(err)
will result in a socket.destroy(err)
call.
The typical flow of an OCSP Request is as follows:
\n'OCSPRequest'
(via the status\ninfo extension in ClientHello).'OCSPRequest'
event, calling the\nlistener if registered.certificate
or issuer
and\nperforms an OCSP request to the CA.OCSPResponse
from the CA and sends it back to the client\nvia the callback
argumentNote: The issuer
can be null
if the certificate is either self-signed or\nthe issuer is not in the root certificates list. (An issuer may be provided\nvia the ca
option when establishing the TLS connection.)
Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.
\nNote: An npm module like asn1.js may be used to parse the certificates.
\n", "params": [] }, { "textRaw": "Event: 'resumeSession'", "type": "event", "name": "resumeSession", "meta": { "added": [ "v0.9.2" ] }, "desc": "The 'resumeSession'
event is emitted when the client requests to resume a\nprevious TLS session. The listener callback is passed two arguments when\ncalled:
sessionId
- The TLS/SSL session identifiercallback
{Function} A callback function to be called when the prior session\nhas been recovered.When called, the event listener may perform a lookup in external storage using\nthe given sessionId
and invoke callback(null, sessionData)
once finished. If\nthe session cannot be resumed (i.e., doesn't exist in storage) the callback may\nbe invoked as callback(null, null)
. Calling callback(err)
will terminate the\nincoming connection and destroy the socket.
Note: Listening for this event will have an effect only on connections\nestablished after the addition of the event listener.
\nThe following illustrates resuming a TLS session:
\nconst tlsSessionStore = {};\nserver.on('newSession', (id, data, cb) => {\n tlsSessionStore[id.toString('hex')] = data;\n cb();\n});\nserver.on('resumeSession', (id, cb) => {\n cb(null, tlsSessionStore[id.toString('hex')] || null);\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'secureConnection'",
"type": "event",
"name": "secureConnection",
"meta": {
"added": [
"v0.3.2"
]
},
"desc": "The 'secureConnection'
event is emitted after the handshaking process for a\nnew connection has successfully completed. The listener callback is passed a\nsingle argument when called:
tlsSocket
{tls.TLSSocket} The established TLS socket.The tlsSocket.authorized
property is a boolean
indicating whether the\nclient has been verified by one of the supplied Certificate Authorities for the\nserver. If tlsSocket.authorized
is false
, then socket.authorizationError
\nis set to describe how authorization failed. Note that depending on the settings\nof the TLS server, unauthorized connections may still be accepted.
The tlsSocket.npnProtocol
and tlsSocket.alpnProtocol
properties are strings\nthat contain the selected NPN and ALPN protocols, respectively. When both NPN\nand ALPN extensions are received, ALPN takes precedence over NPN and the next\nprotocol is selected by ALPN.
When ALPN has no selected protocol, tlsSocket.alpnProtocol
returns false
.
The tlsSocket.servername
property is a string containing the server name\nrequested via SNI.
The server.addContext()
method adds a secure context that will be used if\nthe client request's SNI hostname matches the supplied hostname
(or wildcard).
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.
The server.close()
method stops the server from accepting new connections.
This function operates asynchronously. The 'close'
event will be emitted\nwhen the server has no more open connections.
Returns a Buffer
instance holding the keys currently used for\nencryption/decryption of the TLS Session Tickets
The server.listen()
methods instructs the server to begin accepting\nconnections on the specified port
and hostname
.
This function operates asynchronously. If the callback
is given, it will be\ncalled when the server has started listening.
See net.Server
for more information.
Updates the keys for encryption/decryption of the TLS Session Tickets.
\nNote: The key's Buffer
should be 48 bytes long. See ticketKeys
option in\ntls.createServer for\nmore information on how it is used.
Note: Changes to the ticket keys are effective only for future server\nconnections. Existing or currently pending server connections will use the\nprevious keys.
\n" } ], "properties": [ { "textRaw": "server.connections", "name": "connections", "meta": { "added": [ "v0.3.2" ] }, "desc": "Returns the current number of concurrent connections on the server.
\n" } ] }, { "textRaw": "Class: tls.TLSSocket", "type": "class", "name": "tls.TLSSocket", "meta": { "added": [ "v0.11.4" ] }, "desc": "The tls.TLSSocket
is a subclass of net.Socket
that performs transparent\nencryption of written data and all required TLS negotiation.
Instances of tls.TLSSocket
implement the duplex Stream interface.
Note: Methods that return TLS connection metadata (e.g.\ntls.TLSSocket.getPeerCertificate()
will only return data while the\nconnection is open.
Construct a new tls.TLSSocket
object from an existing TCP socket.
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' }
Returns an object representing the cipher name and the SSL/TLS protocol version\nthat first defined the cipher.
\nFor example: { name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
See SSL_CIPHER_get_name()
and SSL_CIPHER_get_version()
in\nhttps://www.openssl.org/docs/man1.0.2/ssl/SSL_CIPHER_get_name.html for more\ninformation.
Returns an object representing the type, name, and size of parameter of\nan ephemeral key exchange in Perfect Forward Secrecy on a client\nconnection. It returns an empty object when the key exchange is not\nephemeral. As this is only supported on a client socket; null
is returned\nif called on a server socket. The supported types are 'DH'
and 'ECDH'
. The\nname
property is available only when type is 'ECDH'.
For Example: { type: 'ECDH', name: 'prime256v1', size: 256 }
Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the fields of the certificate.
\nIf the full certificate chain was requested, each certificate will include a\nissuerCertificate
property containing an object representing its issuer's\ncertificate.
For example:
\n{ subject:\n { C: 'UK',\n ST: 'Acknack Ltd',\n L: 'Rhys Jones',\n O: 'node.js',\n OU: 'Test TLS Certificate',\n CN: 'localhost' },\n issuer:\n { C: 'UK',\n ST: 'Acknack Ltd',\n L: 'Rhys Jones',\n O: 'node.js',\n OU: 'Test TLS Certificate',\n CN: 'localhost' },\n issuerCertificate:\n { ... another certificate, possibly with a .issuerCertificate ... },\n raw: < RAW DER buffer >,\n valid_from: 'Nov 11 09:52:22 2009 GMT',\n valid_to: 'Nov 6 09:52:22 2029 GMT',\n fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF',\n serialNumber: 'B9B0D332A1AA5635' }\n
\nIf the peer does not provide a certificate, an empty object will be returned.
\n" }, { "textRaw": "tlsSocket.getProtocol()", "type": "method", "name": "getProtocol", "meta": { "added": [ "v5.7.0" ] }, "desc": "Returns a string containing the negotiated SSL/TLS protocol version of the\ncurrent connection. The value 'unknown'
will be returned for connected\nsockets that have not completed the handshaking process. The value null
will\nbe returned for server sockets or disconnected client sockets.
Example responses include:
\nSSLv3
TLSv1
TLSv1.1
TLSv1.2
unknown
See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more\ninformation.
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tlsSocket.getSession()", "type": "method", "name": "getSession", "meta": { "added": [ "v0.11.4" ] }, "desc": "Returns the ASN.1 encoded TLS session or undefined
if no session was\nnegotiated. Can be used to speed up handshake establishment when reconnecting\nto the server.
Returns the TLS session ticket or undefined
if no session was negotiated.
Note: This only works with client TLS sockets. Useful only for debugging, for\nsession reuse provide session
option to tls.connect()
.
The tlsSocket.renegotiate()
method initiates a TLS renegotiation process.\nUpon completion, the callback
function will be passed a single argument\nthat is either an Error
(if the request failed) or null
.
Note: This method can be used to request a peer's certificate after the\nsecure connection has been established.
\nNote: When running as the server, the socket will be destroyed with an error\nafter handshakeTimeout
timeout.
The tlsSocket.setMaxSendFragment()
method sets the maximum TLS fragment size.\nReturns true
if setting the limit succeeded; false
otherwise.
Smaller fragment sizes decrease the buffering latency on the client: larger\nfragments are buffered by the TLS layer until the entire fragment is received\nand its integrity is verified; large fragments can span multiple roundtrips\nand their processing can be delayed due to packet loss or reordering. However,\nsmaller fragments add extra TLS framing bytes and CPU overhead, which may\ndecrease overall server throughput.
\n" } ], "events": [ { "textRaw": "Event: 'OCSPResponse'", "type": "event", "name": "OCSPResponse", "meta": { "added": [ "v0.11.13" ] }, "desc": "The 'OCSPResponse'
event is emitted if the requestOCSP
option was set\nwhen the tls.TLSSocket
was created and an OCSP response has been received.\nThe listener callback is passed a single argument when called:
response
{Buffer} The server's OCSP responseTypically, the response
is a digitally signed object from the server's CA that\ncontains information about server's certificate revocation status.
The 'secureConnect'
event is emitted after the handshaking process for a new\nconnection has successfully completed. The listener callback will be called\nregardless of whether or not the server's certificate has been authorized. It\nis the client's responsibility to check the tlsSocket.authorized
property to\ndetermine if the server certificate was signed by one of the specified CAs. If\ntlsSocket.authorized === false
, then the error can be found by examining the\ntlsSocket.authorizationError
property. If either ALPN or NPN was used,\nthe tlsSocket.alpnProtocol
or tlsSocket.npnProtocol
properties can be\nchecked to determine the negotiated protocol.
Returns true
if the peer certificate was signed by one of the CAs specified\nwhen creating the tls.TLSSocket
instance, otherwise false
.
Returns the reason why the peer's certificate was not been verified. This\nproperty is set only when tlsSocket.authorized === false
.
Always returns true
. This may be used to distinguish TLS sockets from regular\nnet.Socket
instances.
Returns the string representation of the local IP address.
\n" }, { "textRaw": "tlsSocket.localPort", "name": "localPort", "meta": { "added": [ "v0.11.4" ] }, "desc": "Returns the numeric representation of the local port.
\n" }, { "textRaw": "tlsSocket.remoteAddress", "name": "remoteAddress", "meta": { "added": [ "v0.11.4" ] }, "desc": "Returns the string representation of the remote IP address. For example,\n'74.125.127.100'
or '2001:4860:a005::68'
.
Returns the string representation of the remote IP family. 'IPv4'
or 'IPv6'
.
Returns the numeric representation of the remote port. For example, 443
.
Same as tls.connect()
except that port
and host
can be provided\nas arguments instead of options.
Note: A port or host option, if specified, will take precedence over any port\nor host argument.
\n" }, { "textRaw": "tls.connect(path[, options][, callback])", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ] }, "signatures": [ { "params": [ { "textRaw": "`path` {string} Default value for `options.path`. ", "name": "path", "type": "string", "desc": "Default value for `options.path`." }, { "textRaw": "`options` {Object} See [`tls.connect()`][]. ", "name": "options", "type": "Object", "desc": "See [`tls.connect()`][].", "optional": true }, { "textRaw": "`callback` {Function} See [`tls.connect()`][]. ", "name": "callback", "type": "Function", "desc": "See [`tls.connect()`][].", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "Same as tls.connect()
except that path
can be provided\nas an argument instead of an option.
Note: A path option, if specified, will take precedence over the path\nargument.
\n" }, { "textRaw": "tls.connect(options[, callback])", "type": "method", "name": "connect", "meta": { "added": [ "v0.11.3" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`host` {string} Host the client should connect to, defaults to 'localhost'. ", "name": "host", "type": "string", "desc": "Host the client should connect to, defaults to 'localhost'." }, { "textRaw": "`port` {number} Port the client should connect to. ", "name": "port", "type": "number", "desc": "Port the client should connect to." }, { "textRaw": "`path` {string} Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. ", "name": "path", "type": "string", "desc": "Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored." }, { "textRaw": "`socket` {net.Socket} Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `path`, `host` and `port` are ignored. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Note that connection/disconnection/destruction of `socket` is the user's responsibility, calling `tls.connect()` will not cause `net.connect()` to be called. ", "name": "socket", "type": "net.Socket", "desc": "Establish secure connection on a given socket rather than creating a new socket. If this option is specified, `path`, `host` and `port` are ignored. Usually, a socket is already connected when passed to `tls.connect()`, but it can be connected later. Note that connection/disconnection/destruction of `socket` is the user's responsibility, calling `tls.connect()` will not cause `net.connect()` to be called." }, { "textRaw": "`rejectUnauthorized` {boolean} If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`. ", "name": "rejectUnauthorized", "type": "boolean", "desc": "If `true`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if verification fails; `err.code` contains the OpenSSL error code. Defaults to `true`." }, { "textRaw": "`NPNProtocols` {string[]|Buffer[]} An array of strings or `Buffer`s containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`. ", "name": "NPNProtocols", "type": "string[]|Buffer[]", "desc": "An array of strings or `Buffer`s containing supported NPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g. `['hello', 'world']`." }, { "textRaw": "`ALPNProtocols`: {string[]|Buffer[]} An array of strings or `Buffer`s containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler: `['hello', 'world']`.) ", "name": "ALPNProtocols", "type": "string[]|Buffer[]", "desc": "An array of strings or `Buffer`s containing the supported ALPN protocols. `Buffer`s should have the format `[len][name][len][name]...` e.g. `0x05hello0x05world`, where the first byte is the length of the next protocol name. Passing an array is usually much simpler: `['hello', 'world']`.)" }, { "textRaw": "`servername`: {string} Server name for the SNI (Server Name Indication) TLS extension. ", "name": "servername", "type": "string", "desc": "Server name for the SNI (Server Name Indication) TLS extension." }, { "textRaw": "`checkServerIdentity(servername, cert)` {Function} A callback function to be used when checking the server's hostname against the certificate. This should throw an error if verification fails. The method should return `undefined` if the `servername` and `cert` are verified. ", "name": "checkServerIdentity(servername,", "desc": "cert)` {Function} A callback function to be used when checking the server's hostname against the certificate. This should throw an error if verification fails. The method should return `undefined` if the `servername` and `cert` are verified." }, { "textRaw": "`session` {Buffer} A `Buffer` instance, containing TLS session. ", "name": "session", "type": "Buffer", "desc": "A `Buffer` instance, containing TLS session." }, { "textRaw": "`minDHSize` {number} Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`. ", "name": "minDHSize", "type": "number", "desc": "Minimum size of the DH parameter in bits to accept a TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. Defaults to `1024`." }, { "textRaw": "`secureContext`: Optional TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing. ", "name": "secureContext", "desc": "Optional TLS context object created with [`tls.createSecureContext()`][]. If a `secureContext` is _not_ provided, one will be created by passing the entire `options` object to `tls.createSecureContext()`. *Note*: In effect, all [`tls.createSecureContext()`][] options can be provided, but they will be _completely ignored_ unless the `secureContext` option is missing." }, { "textRaw": "...: Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information. ", "name": "...", "desc": "Optional [`tls.createSecureContext()`][] options can be provided, see the `secureContext` option for more information." } ], "name": "options", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ], "desc": "The callback
function, if specified, will be added as a listener for the\n'secureConnect'
event.
tls.connect()
returns a tls.TLSSocket
object.
The following implements a simple "echo server" example:
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n // Necessary only if using the client certificate authentication\n key: fs.readFileSync('client-key.pem'),\n cert: fs.readFileSync('client-cert.pem'),\n\n // Necessary only if the server uses the self-signed certificate\n ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nconst socket = tls.connect(8000, options, () => {\n console.log('client connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n process.stdin.pipe(socket);\n process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', (data) => {\n console.log(data);\n});\nsocket.on('end', () => {\n server.close();\n});\n
\nOr
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n pfx: fs.readFileSync('client.pfx')\n};\n\nconst socket = tls.connect(8000, options, () => {\n console.log('client connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n process.stdin.pipe(socket);\n process.stdin.resume();\n});\nsocket.setEncoding('utf8');\nsocket.on('data', (data) => {\n console.log(data);\n});\nsocket.on('end', () => {\n server.close();\n});\n
\n"
},
{
"textRaw": "tls.createSecureContext(options)",
"type": "method",
"name": "createSecureContext",
"meta": {
"added": [
"v0.11.13"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`pfx` {string|Buffer} Optional PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it. ",
"name": "pfx",
"type": "string|Buffer",
"desc": "Optional PFX or PKCS12 encoded private key and certificate chain. `pfx` is an alternative to providing `key` and `cert` individually. PFX is usually encrypted, if it is, `passphrase` will be used to decrypt it."
},
{
"textRaw": "`key` {string|string[]|Buffer|Buffer[]|Object[]} Optional private keys in PEM format. PEM allows the option of private keys being encrypted. Encrypted keys will be decrypted with `options.passphrase`. Multiple keys using different algorithms can be provided either as an array of unencrypted key strings or buffers, or an array of objects in the form `{pem: The tls.createSecureContext()
method creates a credentials object.
A key is required for ciphers that make use of certificates. Either key
or\npfx
can be used to provide it.
If the 'ca' option is not given, then Node.js will use the default\npublicly trusted list of CAs as given in\nhttp://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.
\n" }, { "textRaw": "tls.createServer([options][, secureConnectionListener])", "type": "method", "name": "createServer", "meta": { "added": [ "v0.3.2" ] }, "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`handshakeTimeout` {number} Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake times out. ", "name": "handshakeTimeout", "type": "number", "desc": "Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. Defaults to `120` seconds. A `'clientError'` is emitted on the `tls.Server` object whenever a handshake times out." }, { "textRaw": "`requestCert` {boolean} If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`. ", "name": "requestCert", "type": "boolean", "desc": "If `true` the server will request a certificate from clients that connect and attempt to verify that certificate. Defaults to `false`." }, { "textRaw": "`rejectUnauthorized` {boolean} If `true` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `false`. ", "name": "rejectUnauthorized", "type": "boolean", "desc": "If `true` the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect if `requestCert` is `true`. Defaults to `false`." }, { "textRaw": "`NPNProtocols` {string[]|Buffer} An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.) ", "name": "NPNProtocols", "type": "string[]|Buffer", "desc": "An array of strings or a `Buffer` naming possible NPN protocols. (Protocols should be ordered by their priority.)" }, { "textRaw": "`ALPNProtocols` {string[]|Buffer} An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client. ", "name": "ALPNProtocols", "type": "string[]|Buffer", "desc": "An array of strings or a `Buffer` naming possible ALPN protocols. (Protocols should be ordered by their priority.) When the server receives both NPN and ALPN extensions from the client, ALPN takes precedence over NPN and the server does not send an NPN extension to the client." }, { "textRaw": "`SNICallback(servername, cb)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below). ", "name": "SNICallback(servername,", "desc": "cb)` {Function} A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called: `servername` and `cb`. `SNICallback` should invoke `cb(null, ctx)`, where `ctx` is a SecureContext instance. (`tls.createSecureContext(...)` can be used to get a proper SecureContext.) If `SNICallback` wasn't provided the default callback with high-level API will be used (see below)." }, { "textRaw": "`sessionTimeout` {number} An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See [SSL_CTX_set_timeout] for more details. ", "name": "sessionTimeout", "type": "number", "desc": "An integer specifying the number of seconds after which the TLS session identifiers and TLS session tickets created by the server will time out. See [SSL_CTX_set_timeout] for more details." }, { "textRaw": "`ticketKeys`: A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. *Note* that this is automatically shared between `cluster` module workers. ", "name": "ticketKeys", "desc": "A 48-byte `Buffer` instance consisting of a 16-byte prefix, a 16-byte HMAC key, and a 16-byte AES key. This can be used to accept TLS session tickets on multiple instances of the TLS server. *Note* that this is automatically shared between `cluster` module workers." }, { "textRaw": "...: Any [`tls.createSecureContext()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required. ", "name": "...", "desc": "Any [`tls.createSecureContext()`][] options can be provided. For servers, the identity options (`pfx` or `key`/`cert`) are usually required." } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`secureConnectionListener` {Function} ", "name": "secureConnectionListener", "type": "Function", "optional": true } ] }, { "params": [ { "name": "options", "optional": true }, { "name": "secureConnectionListener", "optional": true } ] } ], "desc": "Creates a new tls.Server. The secureConnectionListener
, if provided, is\nautomatically set as a listener for the 'secureConnection'
event.
The following illustrates a simple echo server:
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n key: fs.readFileSync('server-key.pem'),\n cert: fs.readFileSync('server-cert.pem'),\n\n // This is necessary only if using the client certificate authentication.\n requestCert: true,\n\n // This is necessary only if the client uses the self-signed certificate.\n ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nconst server = tls.createServer(options, (socket) => {\n console.log('server connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n socket.write('welcome!\\n');\n socket.setEncoding('utf8');\n socket.pipe(socket);\n});\nserver.listen(8000, () => {\n console.log('server bound');\n});\n
\nOr
\nconst tls = require('tls');\nconst fs = require('fs');\n\nconst options = {\n pfx: fs.readFileSync('server.pfx'),\n\n // This is necessary only if using the client certificate authentication.\n requestCert: true,\n\n};\n\nconst server = tls.createServer(options, (socket) => {\n console.log('server connected',\n socket.authorized ? 'authorized' : 'unauthorized');\n socket.write('welcome!\\n');\n socket.setEncoding('utf8');\n socket.pipe(socket);\n});\nserver.listen(8000, () => {\n console.log('server bound');\n});\n
\nThis server can be tested by connecting to it using openssl s_client
:
openssl s_client -connect 127.0.0.1:8000\n
\n"
},
{
"textRaw": "tls.getCiphers()",
"type": "method",
"name": "getCiphers",
"meta": {
"added": [
"v0.10.2"
]
},
"desc": "Returns an array with the names of the supported SSL ciphers.
\nFor example:
\nconsole.log(tls.getCiphers()); // ['AES128-SHA', 'AES256-SHA', ...]\n
\n",
"signatures": [
{
"params": []
}
]
}
],
"properties": [
{
"textRaw": "tls.DEFAULT_ECDH_CURVE",
"name": "DEFAULT_ECDH_CURVE",
"meta": {
"added": [
"v0.11.13"
]
},
"desc": "The default curve name to use for ECDH key agreement in a tls server. The\ndefault value is 'prime256v1'
(NIST P-256). Consult RFC 4492 and\nFIPS.186-4 for more details.
The tty
module provides the tty.ReadStream
and tty.WriteStream
classes.\nIn most cases, it will not be necessary or possible to use this module directly.\nHowever, it can be accessed using:
const tty = require('tty');\n
\nWhen Node.js detects that it is being run inside a text terminal ("TTY")\ncontext, the process.stdin
will, by default, be initialized as an instance of\ntty.ReadStream
and both process.stdout
and process.stderr
will, by\ndefault be instances of tty.WriteStream
. The preferred method of determining\nwhether Node.js is being run within a TTY context is to check that the value of\nthe process.stdout.isTTY
property is true
:
$ node -p -e "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p -e "Boolean(process.stdout.isTTY)" | cat\nfalse\n
\nIn most cases, there should be little to no reason for an application to\ncreate instances of the tty.ReadStream
and tty.WriteStream
classes.
The tty.ReadStream
class is a subclass of net.Socket
that represents the\nreadable side of a TTY. In normal circumstances process.stdin
will be the\nonly tty.ReadStream
instance in a Node.js process and there should be no\nreason to create additional instances.
A boolean
that is true
if the TTY is currently configured to operate as a\nraw device. Defaults to false
.
Allows configuration of tty.ReadStream
so that it operates as a raw device.
When in raw mode, input is always available character-by-character, not\nincluding modifiers. Additionally, all special processing of characters by the\nterminal is disabled, including echoing input characters.\nNote that CTRL
+C
will no longer cause a SIGINT
when in this mode.
mode
{boolean} If true
, configures the tty.ReadStream
to operate as a\nraw device. If false
, configures the tty.ReadStream
to operate in its\ndefault mode. The readStream.isRaw
property will be set to the resulting\nmode.The tty.WriteStream
class is a subclass of net.Socket
that represents the\nwritable side of a TTY. In normal circumstances, process.stdout
and\nprocess.stderr
will be the only tty.WriteStream
instances created for a\nNode.js process and there should be no reason to create additional instances.
The 'resize'
event is emitted whenever either of the writeStream.columns
\nor writeStream.rows
properties have changed. No arguments are passed to the\nlistener callback when called.
process.stdout.on('resize', () => {\n console.log('screen size has changed!');\n console.log(`${process.stdout.columns}x${process.stdout.rows}`);\n});\n
\n",
"params": []
}
],
"properties": [
{
"textRaw": "writeStream.columns",
"name": "columns",
"meta": {
"added": [
"v0.7.7"
]
},
"desc": "A number
specifying the number of columns the TTY currently has. This property\nis updated whenever the 'resize'
event is emitted.
A number
specifying the number of rows the TTY currently has. This property\nis updated whenever the 'resize'
event is emitted.
The tty.isatty()
method returns true
if the given fd
is associated with\na TTY and false
if is not.
The url
module provides utilities for URL resolution and parsing. It can be\naccessed using:
const url = require('url');\n
\n",
"modules": [
{
"textRaw": "URL Strings and URL Objects",
"name": "url_strings_and_url_objects",
"desc": "A URL string is a structured string containing multiple meaningful components.\nWhen parsed, a URL object is returned containing properties for each of these\ncomponents.
\nThe following details each of the components of a parsed URL. The example\n'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
is used to\nillustrate each.
┌─────────────────────────────────────────────────────────────────────────────┐\n│ href │\n├──────────┬┬───────────┬─────────────────┬───────────────────────────┬───────┤\n│ protocol ││ auth │ host │ path │ hash │\n│ ││ ├──────────┬──────┼──────────┬────────────────┤ │\n│ ││ │ hostname │ port │ pathname │ search │ │\n│ ││ │ │ │ ├─┬──────────────┤ │\n│ ││ │ │ │ │ │ query │ │\n" http: // user:pass @ host.com : 8080 /p/a/t/h ? query=string #hash "\n│ ││ │ │ │ │ │ │ │\n└──────────┴┴───────────┴──────────┴──────┴──────────┴─┴──────────────┴───────┘\n(all spaces in the "" line should be ignored -- they are purely for formatting)\n
\n",
"properties": [
{
"textRaw": "urlObject.href",
"name": "href",
"desc": "The href
property is the full URL string that was parsed with both the\nprotocol
and host
components converted to lower-case.
For example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
The protocol
property identifies the URL's lower-cased protocol scheme.
For example: 'http:'
The slashes
property is a boolean
with a value of true
if two ASCII\nforward-slash characters (/
) are required following the colon in the\nprotocol
.
The host
property is the full lower-cased host portion of the URL, including\nthe port
if specified.
For example: 'host.com:8080'
The auth
property is the username and password portion of the URL, also\nreferred to as "userinfo". This string subset follows the protocol
and\ndouble slashes (if present) and precedes the host
component, delimited by an\nASCII "at sign" (@
). The format of the string is {username}[:{password}]
,\nwith the [:{password}]
portion being optional.
For example: 'user:pass'
The hostname
property is the lower-cased host name portion of the host
\ncomponent without the port
included.
For example: 'host.com'
The port
property is the numeric port portion of the host
component.
For example: '8080'
The pathname
property consists of the entire path section of the URL. This\nis everything following the host
(including the port
) and before the start\nof the query
or hash
components, delimited by either the ASCII question\nmark (?
) or hash (#
) characters.
For example '/p/a/t/h'
No decoding of the path string is performed.
\n" }, { "textRaw": "urlObject.search", "name": "search", "desc": "The search
property consists of the entire "query string" portion of the\nURL, including the leading ASCII question mark (?
) character.
For example: '?query=string'
No decoding of the query string is performed.
\n" }, { "textRaw": "urlObject.path", "name": "path", "desc": "The path
property is a concatenation of the pathname
and search
\ncomponents.
For example: '/p/a/t/h?query=string'
No decoding of the path
is performed.
The query
property is either the query string without the leading ASCII\nquestion mark (?
), or an object returned by the querystring
module's\nparse()
method. Whether the query
property is a string or object is\ndetermined by the parseQueryString
argument passed to url.parse()
.
For example: 'query=string'
or {'query': 'string'}
If returned as a string, no decoding of the query string is performed. If\nreturned as an object, both keys and values are decoded.
\n" }, { "textRaw": "urlObject.hash", "name": "hash", "desc": "The hash
property consists of the "fragment" portion of the URL including\nthe leading ASCII hash (#
) character.
For example: '#hash'
URLs are only permitted to contain a certain range of characters. Spaces (' '
)\nand the following characters will be automatically escaped in the\nproperties of URL objects:
< > " ` \\r \\n \\t { } | \\ ^ '\n
\nFor example, the ASCII space character (' '
) is encoded as %20
. The ASCII\nforward slash (/
) character is encoded as %3C
.
The url
module provides an experimental implementation of the\nWHATWG URL Standard as an alternative to the existing url.parse()
API.
const URL = require('url').URL;\nconst myURL = new URL('https://example.org/foo');\n\nconsole.log(myURL.href); // https://example.org/foo\nconsole.log(myURL.protocol); // https:\nconsole.log(myURL.hostname); // example.org\nconsole.log(myURL.pathname); // /foo\n
\nNote: Using the delete
keyword (e.g. delete myURL.protocol
,\ndelete myURL.pathname
, etc) has no effect but will still return true
.
input
{String} The input URL to parsebase
{String | URL} The base URL to resolve against if the input
is not\nabsolute.Creates a new URL
object by parsing the input
relative to the base
. If\nbase
is passed as a string, it will be parsed equivalent to new URL(base)
.
const myURL = new URL('/foo', 'https://example.org/');\n // https://example.org/foo\n
\nA TypeError
will be thrown if the input
or base
are not valid URLs. Note\nthat an effort will be made to coerce the given values into strings. For\ninstance:
const myURL = new URL({toString: () => 'https://example.org/'});\n // https://example.org/\n
\nUnicode characters appearing within the hostname of input
will be\nautomatically converted to ASCII using the Punycode algorithm.
const myURL = new URL('https://你好你好');\n // https://xn--6qqa088eba\n
\nAdditional examples of parsed URLs may be found in the WHATWG URL Standard.
\n", "type": "module", "displayName": "Constructor: new URL(input[, base])" } ], "properties": [ { "textRaw": "url.hash", "name": "hash", "desc": "Gets and sets the fragment portion of the URL.
\nconst myURL = new URL('https://example.org/foo#bar');\nconsole.log(myURL.hash);\n // Prints #bar\n\nmyURL.hash = 'baz';\nconsole.log(myURL.href);\n // Prints https://example.org/foo#baz\n
\nInvalid URL characters included in the value assigned to the hash
property\nare percent-encoded. Note that the selection of\nwhich characters to percent-encode may vary somewhat from what the\nurl.parse()
and url.format()
methods would produce.
Gets and sets the host portion of the URL.
\nconst myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.host);\n // Prints example.org:81\n\nmyURL.host = 'example.com:82';\nconsole.log(myURL.href);\n // Prints https://example.com:82/foo\n
\nInvalid host values assigned to the host
property are ignored.
Gets and sets the hostname portion of the URL. The key difference between\nurl.host
and url.hostname
is that url.hostname
does not include the\nport.
const myURL = new URL('https://example.org:81/foo');\nconsole.log(myURL.hostname);\n // Prints example.org\n\nmyURL.hostname = 'example.com:82';\nconsole.log(myURL.href);\n // Prints https://example.com:81/foo\n
\nInvalid hostname values assigned to the hostname
property are ignored.
Gets and sets the serialized URL.
\nconst myURL = new URL('https://example.org/foo');\nconsole.log(myURL.href);\n // Prints https://example.org/foo\n\nmyURL.href = 'https://example.com/bar'\n // Prints https://example.com/bar\n
\nSetting the value of the href
property to a new value is equivalent to\ncreating a new URL
object using new URL(value)
. Each of the URL
object's\nproperties will be modified.
If the value assigned to the href
property is not a valid URL, a TypeError
\nwill be thrown.
Gets the read-only serialization of the URL's origin. Unicode characters that\nmay be contained within the hostname will be encoded as-is without Punycode\nencoding.
\nconst myURL = new URL('https://example.org/foo/bar?baz');\nconsole.log(myURL.origin);\n // Prints https://example.org\n
\nconst idnURL = new URL('https://你好你好');\nconsole.log(idnURL.origin);\n // Prints https://你好你好\n\nconsole.log(idnURL.hostname);\n // Prints xn--6qqa088eba\n
\n"
},
{
"textRaw": "url.password",
"name": "password",
"desc": "Gets and sets the password portion of the URL.
\nconst myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.password);\n // Prints xyz\n\nmyURL.password = '123';\nconsole.log(myURL.href);\n // Prints https://abc:123@example.com\n
\nInvalid URL characters included in the value assigned to the password
property\nare percent-encoded. Note that the selection of\nwhich characters to percent-encode may vary somewhat from what the\nurl.parse()
and url.format()
methods would produce.
Gets and sets the path portion of the URL.
\nconst myURL = new URL('https://example.org/abc/xyz?123');\nconsole.log(myURL.pathname);\n // Prints /abc/xyz\n\nmyURL.pathname = '/abcdef';\nconsole.log(myURL.href);\n // Prints https://example.org/abcdef?123\n
\nInvalid URL characters included in the value assigned to the pathname
\nproperty are percent-encoded. Note that the\nselection of which characters to percent-encode may vary somewhat from what the\nurl.parse()
and url.format()
methods would produce.
Gets and sets the port portion of the URL. When getting the port, the value\nis returned as a String.
\nconst myURL = new URL('https://example.org:8888');\nconsole.log(myURL.port);\n // Prints 8888\n\nmyURL.port = 1234;\nconsole.log(myURL.href);\n // Prints https://example.org:1234\n
\nThe port value may be set as either a number or as a String containing a number\nin the range 0
to 65535
(inclusive). Setting the value to the default port\nof the URL
objects given protocol
will result in the port
value becoming\nthe empty string (''
).
Invalid URL port values assigned to the port
property are ignored.
Gets and sets the protocol portion of the URL.
\nconst myURL = new URL('https://example.org');\nconsole.log(myURL.protocol);\n // Prints http:\n\nmyURL.protocol = 'ftp';\nconsole.log(myURL.href);\n // Prints ftp://example.org\n
\nInvalid URL protocol values assigned to the protocol
property are ignored.
Gets and sets the serialized query portion of the URL.
\nconst myURL = new URL('https://example.org/abc?123');\nconsole.log(myURL.search);\n // Prints ?123\n\nmyURL.search = 'abc=xyz';\nconsole.log(myURL.href);\n // Prints https://example.org/abc?abc=xyz\n
\nAny invalid URL characters appearing in the value assigned the search
\nproperty will be percent-encoded. Note that the\nselection of which characters to percent-encode may vary somewhat from what the\nurl.parse()
and url.format()
methods would produce.
Gets a URLSearchParams
object representing the\nquery parameters of the URL.
Gets and sets the username portion of the URL.
\nconst myURL = new URL('https://abc:xyz@example.com');\nconsole.log(myURL.username);\n // Prints abc\n\nmyURL.username = '123';\nconsole.log(myURL.href);\n // Prints https://123:xyz@example.com\n
\nAny invalid URL characters appearing in the value assigned the username
\nproperty will be percent-encoded. Note that the\nselection of which characters to percent-encode may vary somewhat from what the\nurl.parse()
and url.format()
methods would produce.
The toString()
method on the URL
object returns the serialized URL. The\nvalue returned is equivalent to that of url.href
.
The URLSearchParams
object provides read and write access to the query of a\nURL
.
const URL = require('url').URL;\nconst myURL = new URL('https://example.org/?abc=123');\nconsole.log(myURL.searchParams.get('abc'));\n // Prints 123\n\nmyURL.searchParams.append('abc', 'xyz');\nconsole.log(myURL.href);\n // Prints https://example.org/?abc=123&abc=xyz\n\nmyURL.searchParams.delete('abc');\nmyURL.searchParams.set('a', 'b');\nconsole.log(myURL.href);\n // Prints https://example.org/?a=b\n
\n",
"methods": [
{
"textRaw": "Constructor: new URLSearchParams([init])",
"name": "Constructor: new URLSearchParams([init])",
"desc": "init
{String} The URL queryAppend a new name-value pair to the query string.
\n" }, { "textRaw": "urlSearchParams.delete(name)", "type": "method", "name": "delete", "signatures": [ { "params": [ { "textRaw": "`name` {String} ", "name": "name", "type": "String" } ] }, { "params": [ { "name": "name" } ] } ], "desc": "Remove all name-value pairs whose name is name
.
Returns an ES6 Iterator over each of the name-value pairs in the query.\nEach item of the iterator is a JavaScript Array. The first item of the Array\nis the name
, the second item of the Array is the value
.
Alias for urlSearchParams\\[\\@\\@iterator\\]()
.
Iterates over each name-value pair in the query and invokes the given function.
\nconst URL = require('url').URL;\nconst myURL = new URL('https://example.org/?a=b&c=d');\nmyURL.searchParams.forEach((value, name) => {\n console.log(name, value);\n});\n
\n"
},
{
"textRaw": "urlSearchParams.get(name)",
"type": "method",
"name": "get",
"signatures": [
{
"return": {
"textRaw": "Returns: {String} or `null` if there is no name-value pair with the given `name`. ",
"name": "return",
"type": "String",
"desc": "or `null` if there is no name-value pair with the given `name`."
},
"params": [
{
"textRaw": "`name` {String} ",
"name": "name",
"type": "String"
}
]
},
{
"params": [
{
"name": "name"
}
]
}
],
"desc": "Returns the value of the first name-value pair whose name is name
.
Returns the values of all name-value pairs whose name is name
.
Returns true
if there is at least one name-value pair whose name is name
.
Returns an ES6 Iterator over the names of each name-value pair.
\n" }, { "textRaw": "urlSearchParams.set(name, value)", "type": "method", "name": "set", "signatures": [ { "params": [ { "textRaw": "`name` {String} ", "name": "name", "type": "String" }, { "textRaw": "`value` {String} ", "name": "value", "type": "String" } ] }, { "params": [ { "name": "name" }, { "name": "value" } ] } ], "desc": "Remove any existing name-value pairs whose name is name
and append a new\nname-value pair.
Returns the search parameters serialized as a URL-encoded string.
\n" }, { "textRaw": "urlSearchParams.values()", "type": "method", "name": "values", "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "Returns an ES6 Iterator over the values of each name-value pair.
\n" }, { "textRaw": "urlSearchParams\\[\\@\\@iterator\\]()", "type": "method", "name": "urlSearchParams\\[\\@\\@iterator\\]", "signatures": [ { "return": { "textRaw": "Returns: {Iterator} ", "name": "return", "type": "Iterator" }, "params": [] }, { "params": [] } ], "desc": "Returns an ES6 Iterator over each of the name-value pairs in the query string.\nEach item of the iterator is a JavaScript Array. The first item of the Array\nis the name
, the second item of the Array is the value
.
Alias for urlSearchParams.entries()
.
Returns the Punycode ASCII serialization of the domain
.
Note: The require('url').domainToAscii()
method is introduced as part of\nthe new URL
implementation but is not part of the WHATWG URL standard.
Returns the Unicode serialization of the domain
.
Note: The require('url').domainToUnicode()
API is introduced as part of the\nthe new URL
implementation but is not part of the WHATWG URL standard.
URLs are permitted to only contain a certain range of characters. Any character\nfalling outside of that range must be encoded. How such characters are encoded,\nand which characters to encode depends entirely on where the character is\nlocated within the structure of the URL. The WHATWG URL Standard uses a more\nselective and fine grained approach to selecting encoded characters than that\nused by the older url.parse()
and url.format()
methods.
The WHATWG algorithm defines three "encoding sets" that describe ranges of\ncharacters that must be percent-encoded:
\nThe simple encode set includes code points in range U+0000 to U+001F\n(inclusive) and all code points greater than U+007E.
\nThe default encode set includes the simple encode set and code points\nU+0020, U+0022, U+0023, U+003C, U+003E, U+003F, U+0060, U+007B, and U+007D.
\nThe userinfo encode set includes the default encode set and code points\nU+002F, U+003A, U+003B, U+003D, U+0040, U+005B, U+005C, U+005D, U+005E, and\nU+007C.
\nThe simple encode set is used primary for URL fragments and certain specific\nconditions for the path. The userinfo encode set is used specifically for\nusername and passwords encoded within the URL. The default encode set is used\nfor all other cases.
\nWhen non-ASCII characters appear within a hostname, the hostname is encoded\nusing the Punycode algorithm. Note, however, that a hostname may contain\nboth Punycode encoded and percent-encoded characters. For example:
\nconst URL = require('url').URL;\nconst myURL = new URL('https://%CF%80.com/foo');\nconsole.log(myURL.href);\n // Prints https://xn--1xa.com/foo\nconsole.log(myURL.origin);\n // Prints https://π.com\n
\n\n\n",
"type": "module",
"displayName": "Percent-Encoding in the WHATWG URL Standard"
}
],
"type": "module",
"displayName": "The WHATWG URL API"
}
],
"methods": [
{
"textRaw": "url.format(urlObject)",
"type": "method",
"name": "format",
"meta": {
"added": [
"v0.1.25"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`urlObject` {Object | String} A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. ",
"name": "urlObject",
"type": "Object | String",
"desc": "A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`."
}
]
},
{
"params": [
{
"name": "urlObject"
}
]
}
],
"desc": "The url.format()
method returns a formatted URL string derived from\nurlObject
.
If urlObject
is not an object or a string, url.parse()
will throw a\nTypeError
.
The formatting process operates as follows:
\nresult
is created.urlObject.protocol
is a string, it is appended as-is to result
.urlObject.protocol
is not undefined
and is not a string, an\nError
is thrown.urlObject.protocol
that do not end with an ASCII\ncolon (:
) character, the literal string :
will be appended to result
.//
\nwill be appended to result
:urlObject.slashes
property is true;urlObject.protocol
begins with http
, https
, ftp
, gopher
, or\nfile
;urlObject.auth
property is truthy, and either\nurlObject.host
or urlObject.hostname
are not undefined
, the value of\nurlObject.auth
will be coerced into a string and appended to result
\n followed by the literal string @
.urlObject.host
property is undefined
then:urlObject.hostname
is a string, it is appended to result
.urlObject.hostname
is not undefined
and is not a string,\nan Error
is thrown.urlObject.port
property value is truthy, and urlObject.hostname
\nis not undefined
::
is appended to result
, andurlObject.port
is coerced to a string and appended to\nresult
.urlObject.host
property value is truthy, the value of\nurlObject.host
is coerced to a string and appended to result
.urlObject.pathname
property is a string that is not an empty string:urlObject.pathname
does not start with an ASCII forward slash\n(/
), then the literal string '/' is appended to result
.urlObject.pathname
is appended to result
.urlObject.pathname
is not undefined
and is not a string, an\nError
is thrown.urlObject.search
property is undefined
and if the urlObject.query
\nproperty is an Object
, the literal string ?
is appended to result
\nfollowed by the output of calling the querystring
module's stringify()
\nmethod passing the value of urlObject.query
.urlObject.search
is a string:urlObject.search
does not start with the ASCII question\nmark (?
) character, the literal string ?
is appended to result
.urlObject.search
is appended to result
.urlObject.search
is not undefined
and is not a string, an\nError
is thrown.urlObject.hash
property is a string:urlObject.hash
does not start with the ASCII hash (#
)\ncharacter, the literal string #
is appended to result
.urlObject.hash
is appended to result
.urlObject.hash
property is not undefined
and is not a\nstring, an Error
is thrown.result
is returned.The url.parse()
method takes a URL string, parses it, and returns a URL\nobject.
The url.resolve()
method resolves a target URL relative to a base URL in a\nmanner similar to that of a Web browser resolving an anchor tag HREF.
For example:
\nurl.resolve('/one/two/three', 'four') // '/one/two/four'\nurl.resolve('http://example.com/', '/one') // 'http://example.com/one'\nurl.resolve('http://example.com/one', '/two') // 'http://example.com/two'\n
\n"
}
],
"type": "module",
"displayName": "URL"
},
{
"textRaw": "util",
"name": "util",
"stability": 2,
"stabilityText": "Stable",
"desc": "The util
module is primarily designed to support the needs of Node.js' own\ninternal APIs. However, many of the utilities are useful for application and\nmodule developers as well. It can be accessed using:
const util = require('util');\n
\n",
"methods": [
{
"textRaw": "util.debuglog(section)",
"type": "method",
"name": "debuglog",
"meta": {
"added": [
"v0.11.3"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Function} The logging function ",
"name": "return",
"type": "Function",
"desc": "The logging function"
},
"params": [
{
"textRaw": "`section` {String} A string identifying the portion of the application for which the `debuglog` function is being created. ",
"name": "section",
"type": "String",
"desc": "A string identifying the portion of the application for which the `debuglog` function is being created."
}
]
},
{
"params": [
{
"name": "section"
}
]
}
],
"desc": "The util.debuglog()
method is used to create a function that conditionally\nwrites debug messages to stderr
based on the existence of the NODE_DEBUG
\nenvironment variable. If the section
name appears within the value of that\nenvironment variable, then the returned function operates similar to\nconsole.error()
. If not, then the returned function is a no-op.
For example:
\nconst util = require('util');\nconst debuglog = util.debuglog('foo');\n\ndebuglog('hello from foo [%d]', 123);\n
\nIf this program is run with NODE_DEBUG=foo
in the environment, then\nit will output something like:
FOO 3245: hello from foo [123]\n
\nwhere 3245
is the process id. If it is not run with that\nenvironment variable set, then it will not print anything.
Multiple comma-separated section
names may be specified in the NODE_DEBUG
\nenvironment variable. For example: NODE_DEBUG=fs,net,tls
.
The util.deprecate()
method wraps the given function
or class in such a way that\nit is marked as deprecated.
const util = require('util');\n\nexports.puts = util.deprecate(function() {\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
\nWhen called, util.deprecate()
will return a function that will emit a\nDeprecationWarning
using the process.on('warning')
event. By default,\nthis warning will be emitted and printed to stderr
exactly once, the first\ntime it is called. After the warning is emitted, the wrapped function
\nis called.
If either the --no-deprecation
or --no-warnings
command line flags are\nused, or if the process.noDeprecation
property is set to true
prior to\nthe first deprecation warning, the util.deprecate()
method does nothing.
If the --trace-deprecation
or --trace-warnings
command line flags are set,\nor the process.traceDeprecation
property is set to true
, a warning and a\nstack trace are printed to stderr
the first time the deprecated function is\ncalled.
If the --throw-deprecation
command line flag is set, or the\nprocess.throwDeprecation
property is set to true
, then an exception will be\nthrown when the deprecated function is called.
The --throw-deprecation
command line flag and process.throwDeprecation
\nproperty take precedence over --trace-deprecation
and\nprocess.traceDeprecation
.
The util.format()
method returns a formatted string using the first argument\nas a printf
-like format.
The first argument is a string containing zero or more placeholder tokens.\nEach placeholder token is replaced with the converted value from the\ncorresponding argument. Supported placeholders are:
\n%s
- String.%d
- Number (both integer and float).%j
- JSON. Replaced with the string '[Circular]'
if the argument\ncontains circular references.%%
- single percent sign ('%'
). This does not consume an argument.If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.
\nutil.format('%s:%s', 'foo');\n// Returns: 'foo:%s'\n
\nIf there are more arguments passed to the util.format()
method than the\nnumber of placeholders, the extra arguments are coerced into strings (for\nobjects and symbols, util.inspect()
is used) then concatenated to the\nreturned string, each delimited by a space.
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'\n
\nIf the first argument is not a format string then util.format()
returns\na string that is the concatenation of all arguments separated by spaces.\nEach argument is converted to a string using util.inspect()
.
util.format(1, 2, 3); // '1 2 3'\n
\n"
},
{
"textRaw": "util.inherits(constructor, superConstructor)",
"type": "method",
"name": "inherits",
"meta": {
"added": [
"v0.3.0"
]
},
"desc": "Note: usage of util.inherits()
is discouraged. Please use the ES6 class
and\nextends
keywords to get language level inheritance support. Also note that\nthe two styles are semantically incompatible.
constructor
{Function}superConstructor
{Function}Inherit the prototype methods from one constructor into another. The\nprototype of constructor
will be set to a new object created from\nsuperConstructor
.
As an additional convenience, superConstructor
will be accessible\nthrough the constructor.super_
property.
const util = require('util');\nconst EventEmitter = require('events');\n\nfunction MyStream() {\n EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, EventEmitter);\n\nMyStream.prototype.write = function(data) {\n this.emit('data', data);\n};\n\nconst stream = new MyStream();\n\nconsole.log(stream instanceof EventEmitter); // true\nconsole.log(MyStream.super_ === EventEmitter); // true\n\nstream.on('data', (data) => {\n console.log(`Received data: "${data}"`);\n});\nstream.write('It works!'); // Received data: "It works!"\n
\nES6 example using class
and extends
const EventEmitter = require('events');\n\nclass MyStream extends EventEmitter {\n constructor() {\n super();\n }\n write(data) {\n this.emit('data', data);\n }\n}\n\nconst stream = new MyStream();\n\nstream.on('data', (data) => {\n console.log(`Received data: "${data}"`);\n});\nstream.write('With ES6');\n
\n",
"signatures": [
{
"params": [
{
"name": "constructor"
},
{
"name": "superConstructor"
}
]
}
]
},
{
"textRaw": "util.inspect(object[, options])",
"type": "method",
"name": "inspect",
"meta": {
"added": [
"v0.3.0"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} Any JavaScript primitive or Object. ",
"name": "object",
"type": "any",
"desc": "Any JavaScript primitive or Object."
},
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`showHidden` {boolean} If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`. ",
"name": "showHidden",
"type": "boolean",
"desc": "If `true`, the `object`'s non-enumerable symbols and properties will be included in the formatted result. Defaults to `false`."
},
{
"textRaw": "`depth` {number} Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`. ",
"name": "depth",
"type": "number",
"desc": "Specifies the number of times to recurse while formatting the `object`. This is useful for inspecting large complicated objects. Defaults to `2`. To make it recurse indefinitely pass `null`."
},
{
"textRaw": "`colors` {boolean} If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see [Customizing `util.inspect` colors][]. ",
"name": "colors",
"type": "boolean",
"desc": "If `true`, the output will be styled with ANSI color codes. Defaults to `false`. Colors are customizable, see [Customizing `util.inspect` colors][]."
},
{
"textRaw": "`customInspect` {boolean} If `false`, then custom `inspect(depth, opts)` functions exported on the `object` being inspected will not be called. Defaults to `true`. ",
"name": "customInspect",
"type": "boolean",
"desc": "If `false`, then custom `inspect(depth, opts)` functions exported on the `object` being inspected will not be called. Defaults to `true`."
},
{
"textRaw": "`showProxy` {boolean} If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`. ",
"name": "showProxy",
"type": "boolean",
"desc": "If `true`, then objects and functions that are `Proxy` objects will be introspected to show their `target` and `handler` objects. Defaults to `false`."
},
{
"textRaw": "`maxArrayLength` {number} Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements. ",
"name": "maxArrayLength",
"type": "number",
"desc": "Specifies the maximum number of array and `TypedArray` elements to include when formatting. Defaults to `100`. Set to `null` to show all array elements. Set to `0` or negative to show no array elements."
},
{
"textRaw": "`breakLength` {number} The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to 60 for legacy compatibility. ",
"name": "breakLength",
"type": "number",
"desc": "The length at which an object's keys are split across multiple lines. Set to `Infinity` to format an object as a single line. Defaults to 60 for legacy compatibility."
}
],
"name": "options",
"type": "Object",
"optional": true
}
]
},
{
"params": [
{
"name": "object"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "The util.inspect()
method returns a string representation of object
that is\nprimarily useful for debugging. Additional options
may be passed that alter\ncertain aspects of the formatted string.
The following example inspects all properties of the util
object:
const util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));\n
\nValues may supply their own custom inspect(depth, opts)
functions, when\ncalled these receive the current depth
in the recursive inspection, as well as\nthe options object passed to util.inspect()
.
Color output (if enabled) of util.inspect
is customizable globally\nvia the util.inspect.styles
and util.inspect.colors
properties.
util.inspect.styles
is a map associating a style name to a color from\nutil.inspect.colors
.
The default styles and associated colors are:
\nnumber
- yellow
boolean
- yellow
string
- green
date
- magenta
regexp
- red
null
- bold
undefined
- grey
special
- cyan
(only applied to functions at this time)name
- (no styling)The predefined color codes are: white
, grey
, black
, blue
, cyan
,\ngreen
, magenta
, red
and yellow
. There are also bold
, italic
,\nunderline
and inverse
codes.
Color styling uses ANSI control codes that may not be supported on all\nterminals.
\n" }, { "textRaw": "Custom inspection functions on Objects", "name": "Custom inspection functions on Objects", "type": "misc", "desc": "Objects may also define their own [util.inspect.custom](depth, opts)
\n(or, equivalently inspect(depth, opts)
) function that util.inspect()
will\ninvoke and use the result of when inspecting the object:
const util = require('util');\n\nclass Box {\n constructor(value) {\n this.value = value;\n }\n\n inspect(depth, options) {\n if (depth < 0) {\n return options.stylize('[Box]', 'special');\n }\n\n const newOptions = Object.assign({}, options, {\n depth: options.depth === null ? null : options.depth - 1\n });\n\n // Five space padding because that's the size of "Box< ".\n const padding = ' '.repeat(5);\n const inner = util.inspect(this.value, newOptions).replace(/\\n/g, '\\n' + padding);\n return options.stylize('Box', 'special') + '< ' + inner + ' >';\n }\n}\n\nconst box = new Box(true);\n\nutil.inspect(box);\n// Returns: "Box< true >"\n
\nCustom [util.inspect.custom](depth, opts)
functions typically return a string\nbut may return a value of any type that will be formatted accordingly by\nutil.inspect()
.
const util = require('util');\n\nconst obj = { foo: 'this will not show up in the inspect() output' };\nobj[util.inspect.custom] = function(depth) {\n return { bar: 'baz' };\n};\n\nutil.inspect(obj);\n// Returns: "{ bar: 'baz' }"\n
\nA custom inspection method can alternatively be provided by exposing\nan inspect(depth, opts)
method on the object:
const util = require('util');\n\nconst obj = { foo: 'this will not show up in the inspect() output' };\nobj.inspect = function(depth) {\n return { bar: 'baz' };\n};\n\nutil.inspect(obj);\n// Returns: "{ bar: 'baz' }"\n
\n"
}
],
"modules": [
{
"textRaw": "util.inspect.defaultOptions",
"name": "util.inspect.defaultoptions",
"meta": {
"added": [
"v6.4.0"
]
},
"desc": "The defaultOptions
value allows customization of the default options used by\nutil.inspect
. This is useful for functions like console.log
or\nutil.format
which implicitly call into util.inspect
. It shall be set to an\nobject containing one or more valid util.inspect()
options. Setting\noption properties directly is also supported.
const util = require('util');\nconst arr = Array(101);\n\nconsole.log(arr); // logs the truncated array\nutil.inspect.defaultOptions.maxArrayLength = null;\nconsole.log(arr); // logs the full array\n
\n",
"type": "module",
"displayName": "util.inspect.defaultOptions"
},
{
"textRaw": "util.inspect.custom",
"name": "util.inspect.custom",
"meta": {
"added": [
"v6.6.0"
]
},
"desc": "A Symbol that can be used to declare custom inspect functions, see\nCustom inspection functions on Objects.
\n", "type": "module", "displayName": "util.inspect.custom" } ] } ], "modules": [ { "textRaw": "Deprecated APIs", "name": "deprecated_apis", "desc": "The following APIs have been deprecated and should no longer be used. Existing\napplications and modules should be updated to find alternative approaches.
\n", "methods": [ { "textRaw": "util.debug(string)", "type": "method", "name": "debug", "meta": { "added": [ "v0.3.0" ], "deprecated": [ "v0.11.3" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`console.error()`][] instead.", "signatures": [ { "params": [ { "textRaw": "`string` {String} The message to print to `stderr` ", "name": "string", "type": "String", "desc": "The message to print to `stderr`" } ] }, { "params": [ { "name": "string" } ] } ], "desc": "Deprecated predecessor of console.error
.
Deprecated predecessor of console.error
.
Internal alias for Array.isArray
.
Returns true
if the given object
is an Array
. Otherwise, returns false
.
const util = require('util');\n\nutil.isArray([]);\n// Returns: true\nutil.isArray(new Array);\n// Returns: true\nutil.isArray({});\n// Returns: false\n
\n"
},
{
"textRaw": "util.isBoolean(object)",
"type": "method",
"name": "isBoolean",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a Boolean
. Otherwise, returns false
.
const util = require('util');\n\nutil.isBoolean(1);\n// Returns: false\nutil.isBoolean(0);\n// Returns: false\nutil.isBoolean(false);\n// Returns: true\n
\n"
},
{
"textRaw": "util.isBuffer(object)",
"type": "method",
"name": "isBuffer",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated: Use [`Buffer.isBuffer()`][] instead.",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a Buffer
. Otherwise, returns false
.
const util = require('util');\n\nutil.isBuffer({ length: 0 });\n// Returns: false\nutil.isBuffer([]);\n// Returns: false\nutil.isBuffer(Buffer.from('hello world'));\n// Returns: true\n
\n"
},
{
"textRaw": "util.isDate(object)",
"type": "method",
"name": "isDate",
"meta": {
"added": [
"v0.6.0"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a Date
. Otherwise, returns false
.
const util = require('util');\n\nutil.isDate(new Date());\n// Returns: true\nutil.isDate(Date());\n// false (without 'new' returns a String)\nutil.isDate({});\n// Returns: false\n
\n"
},
{
"textRaw": "util.isError(object)",
"type": "method",
"name": "isError",
"meta": {
"added": [
"v0.6.0"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is an Error
. Otherwise, returns\nfalse
.
const util = require('util');\n\nutil.isError(new Error());\n// Returns: true\nutil.isError(new TypeError());\n// Returns: true\nutil.isError({ name: 'Error', message: 'an error occurred' });\n// Returns: false\n
\nNote that this method relies on Object.prototype.toString()
behavior. It is\npossible to obtain an incorrect result when the object
argument manipulates\n@@toStringTag
.
const util = require('util');\nconst obj = { name: 'Error', message: 'an error occurred' };\n\nutil.isError(obj);\n// Returns: false\nobj[Symbol.toStringTag] = 'Error';\nutil.isError(obj);\n// Returns: true\n
\n"
},
{
"textRaw": "util.isFunction(object)",
"type": "method",
"name": "isFunction",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a Function
. Otherwise, returns\nfalse
.
const util = require('util');\n\nfunction Foo() {}\nconst Bar = function() {};\n\nutil.isFunction({});\n// Returns: false\nutil.isFunction(Foo);\n// Returns: true\nutil.isFunction(Bar);\n// Returns: true\n
\n"
},
{
"textRaw": "util.isNull(object)",
"type": "method",
"name": "isNull",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is strictly null
. Otherwise, returns\nfalse
.
const util = require('util');\n\nutil.isNull(0);\n// Returns: false\nutil.isNull(undefined);\n// Returns: false\nutil.isNull(null);\n// Returns: true\n
\n"
},
{
"textRaw": "util.isNullOrUndefined(object)",
"type": "method",
"name": "isNullOrUndefined",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is null
or undefined
. Otherwise,\nreturns false
.
const util = require('util');\n\nutil.isNullOrUndefined(0);\n// Returns: false\nutil.isNullOrUndefined(undefined);\n// Returns: true\nutil.isNullOrUndefined(null);\n// Returns: true\n
\n"
},
{
"textRaw": "util.isNumber(object)",
"type": "method",
"name": "isNumber",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a Number
. Otherwise, returns false
.
const util = require('util');\n\nutil.isNumber(false);\n// Returns: false\nutil.isNumber(Infinity);\n// Returns: true\nutil.isNumber(0);\n// Returns: true\nutil.isNumber(NaN);\n// Returns: true\n
\n"
},
{
"textRaw": "util.isObject(object)",
"type": "method",
"name": "isObject",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is strictly an Object
and not a\nFunction
. Otherwise, returns false
.
const util = require('util');\n\nutil.isObject(5);\n// Returns: false\nutil.isObject(null);\n// Returns: false\nutil.isObject({});\n// Returns: true\nutil.isObject(function(){});\n// Returns: false\n
\n"
},
{
"textRaw": "util.isPrimitive(object)",
"type": "method",
"name": "isPrimitive",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a primitive type. Otherwise, returns\nfalse
.
const util = require('util');\n\nutil.isPrimitive(5);\n// Returns: true\nutil.isPrimitive('foo');\n// Returns: true\nutil.isPrimitive(false);\n// Returns: true\nutil.isPrimitive(null);\n// Returns: true\nutil.isPrimitive(undefined);\n// Returns: true\nutil.isPrimitive({});\n// Returns: false\nutil.isPrimitive(function() {});\n// Returns: false\nutil.isPrimitive(/^$/);\n// Returns: false\nutil.isPrimitive(new Date());\n// Returns: false\n
\n"
},
{
"textRaw": "util.isRegExp(object)",
"type": "method",
"name": "isRegExp",
"meta": {
"added": [
"v0.6.0"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a RegExp
. Otherwise, returns false
.
const util = require('util');\n\nutil.isRegExp(/some regexp/);\n// Returns: true\nutil.isRegExp(new RegExp('another regexp'));\n// Returns: true\nutil.isRegExp({});\n// Returns: false\n
\n"
},
{
"textRaw": "util.isString(object)",
"type": "method",
"name": "isString",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a string
. Otherwise, returns false
.
const util = require('util');\n\nutil.isString('');\n// Returns: true\nutil.isString('foo');\n// Returns: true\nutil.isString(String('foo'));\n// Returns: true\nutil.isString(5);\n// Returns: false\n
\n"
},
{
"textRaw": "util.isSymbol(object)",
"type": "method",
"name": "isSymbol",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is a Symbol
. Otherwise, returns false
.
const util = require('util');\n\nutil.isSymbol(5);\n// Returns: false\nutil.isSymbol('foo');\n// Returns: false\nutil.isSymbol(Symbol('foo'));\n// Returns: true\n
\n"
},
{
"textRaw": "util.isUndefined(object)",
"type": "method",
"name": "isUndefined",
"meta": {
"added": [
"v0.11.5"
],
"deprecated": [
"v4.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated",
"signatures": [
{
"params": [
{
"textRaw": "`object` {any} ",
"name": "object",
"type": "any"
}
]
},
{
"params": [
{
"name": "object"
}
]
}
],
"desc": "Returns true
if the given object
is undefined
. Otherwise, returns false
.
const util = require('util');\n\nconst foo = undefined;\nutil.isUndefined(5);\n// Returns: false\nutil.isUndefined(foo);\n// Returns: true\nutil.isUndefined(null);\n// Returns: false\n
\n"
},
{
"textRaw": "util.log(string)",
"type": "method",
"name": "log",
"meta": {
"added": [
"v0.3.0"
],
"deprecated": [
"v6.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated: Use a third party module instead.",
"signatures": [
{
"params": [
{
"textRaw": "`string` {String} ",
"name": "string",
"type": "String"
}
]
},
{
"params": [
{
"name": "string"
}
]
}
],
"desc": "The util.log()
method prints the given string
to stdout
with an included\ntimestamp.
const util = require('util');\n\nutil.log('Timestamped message.');\n
\n"
},
{
"textRaw": "util.print([...strings])",
"type": "method",
"name": "print",
"meta": {
"added": [
"v0.3.0"
],
"deprecated": [
"v0.11.3"
]
},
"stability": 0,
"stabilityText": "Deprecated: Use [`console.log()`][] instead.",
"desc": "Deprecated predecessor of console.log
.
Deprecated predecessor of console.log
.
The util._extend()
method was never intended to be used outside of internal\nNode.js modules. The community found and used it anyway.
It is deprecated and should not be used in new code. JavaScript comes with very\nsimilar built-in functionality through Object.assign()
.
The v8
module exposes APIs that are specific to the version of V8\nbuilt into the Node.js binary. It can be accessed using:
const v8 = require('v8');\n
\nNote: The APIs and implementation are subject to change at any time.
\n", "methods": [ { "textRaw": "v8.getHeapStatistics()", "type": "method", "name": "getHeapStatistics", "meta": { "added": [ "v1.0.0" ] }, "desc": "Returns an object with the following properties:
\ntotal_heap_size
{number}total_heap_size_executable
{number}total_physical_size
{number}total_available_size
{number}used_heap_size
{number}heap_size_limit
{number}malloced_memory
{number}peak_malloced_memory
{number}does_zap_garbage
{number}does_zap_garbage
is a 0/1 boolean, which signifies whether the --zap_code_space
\noption is enabled or not. This makes V8 overwrite heap garbage with a bit\npattern. The RSS footprint (resident memory set) gets bigger because it\ncontinuously touches all heap pages and that makes them less likely to get\nswapped out by the operating system.
For example:
\n{\n total_heap_size: 7326976,\n total_heap_size_executable: 4194304,\n total_physical_size: 7326976,\n total_available_size: 1152656,\n used_heap_size: 3476208,\n heap_size_limit: 1535115264,\n malloced_memory: 16384,\n peak_malloced_memory: 1127496,\n does_zap_garbage: 0\n}\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "v8.getHeapSpaceStatistics()",
"type": "method",
"name": "getHeapSpaceStatistics",
"meta": {
"added": [
"v6.0.0"
]
},
"desc": "Returns statistics about the V8 heap spaces, i.e. the segments which make up\nthe V8 heap. Neither the ordering of heap spaces, nor the availability of a\nheap space can be guaranteed as the statistics are provided via the V8\nGetHeapSpaceStatistics
function and may change from one V8 version to the\nnext.
The value returned is an array of objects containing the following properties:
\nspace_name
{string}space_size
{number}space_used_size
{number}space_available_size
{number}physical_space_size
{number}For example:
\n[\n {\n "space_name": "new_space",\n "space_size": 2063872,\n "space_used_size": 951112,\n "space_available_size": 80824,\n "physical_space_size": 2063872\n },\n {\n "space_name": "old_space",\n "space_size": 3090560,\n "space_used_size": 2493792,\n "space_available_size": 0,\n "physical_space_size": 3090560\n },\n {\n "space_name": "code_space",\n "space_size": 1260160,\n "space_used_size": 644256,\n "space_available_size": 960,\n "physical_space_size": 1260160\n },\n {\n "space_name": "map_space",\n "space_size": 1094160,\n "space_used_size": 201608,\n "space_available_size": 0,\n "physical_space_size": 1094160\n },\n {\n "space_name": "large_object_space",\n "space_size": 0,\n "space_used_size": 0,\n "space_available_size": 1490980608,\n "physical_space_size": 0\n }\n]\n
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "v8.setFlagsFromString(string)",
"type": "method",
"name": "setFlagsFromString",
"meta": {
"added": [
"v1.0.0"
]
},
"desc": "The v8.setFlagsFromString()
method can be used to programmatically set\nV8 command line flags. This method should be used with care. Changing settings\nafter the VM has started may result in unpredictable behavior, including\ncrashes and data loss; or it may simply do nothing.
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.
Usage:
\n// Print GC events to stdout for one minute.\nconst v8 = require('v8');\nv8.setFlagsFromString('--trace_gc');\nsetTimeout(function() { v8.setFlagsFromString('--notrace_gc'); }, 60e3);\n
\n\n\n",
"signatures": [
{
"params": [
{
"name": "string"
}
]
}
]
}
],
"type": "module",
"displayName": "V8"
},
{
"textRaw": "Executing JavaScript",
"name": "vm",
"stability": 2,
"stabilityText": "Stable",
"desc": "The vm
module provides APIs for compiling and running code within V8 Virtual\nMachine contexts. It can be accessed using:
const vm = require('vm');\n
\nJavaScript code can be compiled and run immediately or compiled, saved, and run\nlater.
\n", "classes": [ { "textRaw": "Class: vm.Script", "type": "class", "name": "vm.Script", "meta": { "added": [ "v0.3.1" ] }, "desc": "Instances of the vm.Script
class contain precompiled scripts that can be\nexecuted in specific sandboxes (or "contexts").
Creating a new vm.Script
object compiles code
but does not run it. The\ncompiled vm.Script
can be run later multiple times. It is important to note\nthat the code
is not bound to any global object; rather, it is bound before\neach run, just for that run.
Runs the compiled code contained by the vm.Script
object within the given\ncontextifiedSandbox
and returns the result. Running code does not have access\nto local scope.
The following example compiles code that increments a global variable, sets\nthe value of another global variable, then execute the code multiple times.\nThe globals are contained in the sandbox
object.
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = {\n animal: 'cat',\n count: 2\n};\n\nconst script = new vm.Script('count += 1; name = "kitty";');\n\nconst context = new vm.createContext(sandbox);\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
\n"
},
{
"textRaw": "script.runInNewContext([sandbox][, options])",
"type": "method",
"name": "runInNewContext",
"meta": {
"added": [
"v0.3.1"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`sandbox` {Object} An object that will be [contextified][]. If `undefined`, a new object will be created. ",
"name": "sandbox",
"type": "Object",
"desc": "An object that will be [contextified][]. If `undefined`, a new object will be created.",
"optional": true
},
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ",
"name": "filename",
"type": "string",
"desc": "Specifies the filename used in stack traces produced by this script."
},
{
"textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. ",
"name": "lineOffset",
"type": "number",
"desc": "Specifies the line number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ",
"name": "columnOffset",
"type": "number",
"desc": "Specifies the column number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ",
"name": "displayErrors",
"type": "boolean",
"desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace."
},
{
"textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ",
"name": "timeout",
"type": "number",
"desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown."
}
],
"name": "options",
"type": "Object",
"optional": true
}
]
},
{
"params": [
{
"name": "sandbox",
"optional": true
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "First contextifies the given sandbox
, runs the compiled code contained by\nthe vm.Script
object within the created sandbox, and returns the result.\nRunning code does not have access to local scope.
The following example compiles code that sets a global variable, then executes\nthe code multiple times in different contexts. The globals are set on and\ncontained within each individual sandbox
.
const util = require('util');\nconst vm = require('vm');\n\nconst script = new vm.Script('globalVar = "set"');\n\nconst sandboxes = [{}, {}, {}];\nsandboxes.forEach((sandbox) => {\n script.runInNewContext(sandbox);\n});\n\nconsole.log(util.inspect(sandboxes));\n\n// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]\n
\n"
},
{
"textRaw": "script.runInThisContext([options])",
"type": "method",
"name": "runInThisContext",
"meta": {
"added": [
"v0.3.1"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} ",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ",
"name": "filename",
"type": "string",
"desc": "Specifies the filename used in stack traces produced by this script."
},
{
"textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. ",
"name": "lineOffset",
"type": "number",
"desc": "Specifies the line number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ",
"name": "columnOffset",
"type": "number",
"desc": "Specifies the column number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ",
"name": "displayErrors",
"type": "boolean",
"desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace."
},
{
"textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ",
"name": "timeout",
"type": "number",
"desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown."
}
],
"name": "options",
"type": "Object",
"optional": true
}
]
},
{
"params": [
{
"name": "options",
"optional": true
}
]
}
],
"desc": "Runs the compiled code contained by the vm.Script
within the context of the\ncurrent global
object. Running code does not have access to local scope, but\ndoes have access to the current global
object.
The following example compiles code that increments a global
variable then\nexecutes that code multiple times:
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
\n"
}
]
}
],
"methods": [
{
"textRaw": "vm.createContext([sandbox])",
"type": "method",
"name": "createContext",
"meta": {
"added": [
"v0.3.1"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`sandbox` {Object} ",
"name": "sandbox",
"type": "Object",
"optional": true
}
]
},
{
"params": [
{
"name": "sandbox",
"optional": true
}
]
}
],
"desc": "If given a sandbox
object, the vm.createContext()
method will prepare\nthat sandbox so that it can be used in calls to\nvm.runInContext()
or script.runInContext()
. Inside such scripts,\nthe sandbox
object will be the global object, retaining all of its existing\nproperties but also having the built-in objects and functions any standard\nglobal object has. Outside of scripts run by the vm module, global variables\nwill remain unchanged.
const util = require('util');\nconst vm = require('vm');\n\nvar globalVar = 3;\n\nconst sandbox = { globalVar: 1 };\nvm.createContext(sandbox);\n\nvm.runInContext('globalVar *= 2;', sandbox);\n\nconsole.log(util.inspect(sandbox)); // 2\n\nconsole.log(util.inspect(globalVar)); // 3\n
\nIf sandbox
is omitted (or passed explicitly as undefined
), a new, empty\ncontextified sandbox object will be returned.
The vm.createContext()
method is primarily useful for creating a single\nsandbox that can be used to run multiple scripts. For instance, if emulating a\nweb browser, the method can be used to create a single sandbox representing a\nwindow's global object, then run all <script>
tags together within the context\nof that sandbox.
Returns true
if the given sandbox
object has been contextified using\nvm.createContext()
.
The vm.runInContext()
method compiles code
, runs it within the context of\nthe contextifiedSandbox
, then returns the result. Running code does not have\naccess to the local scope. The contextifiedSandbox
object must have been\npreviously contextified using the vm.createContext()
method.
The following example compiles and executes different scripts using a single\ncontextified object:
\nconst 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
\n"
},
{
"textRaw": "vm.runInDebugContext(code)",
"type": "method",
"name": "runInDebugContext",
"meta": {
"added": [
"v0.11.14"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`code` {string} The JavaScript code to compile and run. ",
"name": "code",
"type": "string",
"desc": "The JavaScript code to compile and run."
}
]
},
{
"params": [
{
"name": "code"
}
]
}
],
"desc": "The vm.runInDebugContext()
method compiles and executes code
inside the V8\ndebug context. The primary use case is to gain access to the V8 Debug
object:
const vm = require('vm');\nconst Debug = vm.runInDebugContext('Debug');\nconsole.log(Debug.findScript(process.emit).name); // 'events.js'\nconsole.log(Debug.findScript(process.exit).name); // 'internal/process.js'\n
\nNote: The debug context and object are intrinsically tied to V8's debugger\nimplementation and may change (or even be removed) without prior warning.
\nThe Debug
object can also be made available using the V8-specific\n--expose_debug_as=
command line option.
The vm.runInNewContext()
first contextifies the given sandbox
object (or\ncreates a new sandbox
if passed as undefined
), compiles the code
, runs it\nwithin the context of the created context, then returns the result. Running code\ndoes not have access to the local scope.
The following example compiles and executes code that increments a global\nvariable and sets a new one. These globals are contained in the sandbox
.
const util = require('util');\nconst vm = require('vm');\n\nconst sandbox = {\n animal: 'cat',\n count: 2\n};\n\nvm.runInNewContext('count += 1; name = "kitty"', sandbox);\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }\n
\n"
},
{
"textRaw": "vm.runInThisContext(code[, options])",
"type": "method",
"name": "runInThisContext",
"meta": {
"added": [
"v0.3.1"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`code` {string} The JavaScript code to compile and run. ",
"name": "code",
"type": "string",
"desc": "The JavaScript code to compile and run."
},
{
"textRaw": "`options` ",
"options": [
{
"textRaw": "`filename` {string} Specifies the filename used in stack traces produced by this script. ",
"name": "filename",
"type": "string",
"desc": "Specifies the filename used in stack traces produced by this script."
},
{
"textRaw": "`lineOffset` {number} Specifies the line number offset that is displayed in stack traces produced by this script. ",
"name": "lineOffset",
"type": "number",
"desc": "Specifies the line number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`columnOffset` {number} Specifies the column number offset that is displayed in stack traces produced by this script. ",
"name": "columnOffset",
"type": "number",
"desc": "Specifies the column number offset that is displayed in stack traces produced by this script."
},
{
"textRaw": "`displayErrors` {boolean} When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. ",
"name": "displayErrors",
"type": "boolean",
"desc": "When `true`, if an [`Error`][] error occurs while compiling the `code`, the line of code causing the error is attached to the stack trace."
},
{
"textRaw": "`timeout` {number} Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown. ",
"name": "timeout",
"type": "number",
"desc": "Specifies the number of milliseconds to execute `code` before terminating execution. If execution is terminated, an [`Error`][] will be thrown."
}
],
"name": "options",
"optional": true
}
]
},
{
"params": [
{
"name": "code"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "vm.runInThisContext()
compiles code
, runs it within the context of the\ncurrent global
and returns the result. Running code does not have access to\nlocal scope, but does have access to the current global
object.
The following example illustrates using both vm.runInThisContext()
and\nthe JavaScript eval()
function to run the same code:
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
\nBecause vm.runInThisContext()
does not have access to the local scope,\nlocalVar
is unchanged. In contrast, eval()
does have access to the\nlocal scope, so the value localVar
is changed. In this way\nvm.runInThisContext()
is much like an indirect eval()
call, e.g.\n(0,eval)('code')
.
When using either script.runInThisContext()
or vm.runInThisContext()
, the\ncode is executed within the current V8 global context. The code passed\nto this VM context will have its own isolated scope.
In order to run a simple web server using the http
module the code passed to\nthe context must either call require('http')
on its own, or have a reference\nto the http
module passed to it. For instance:
'use strict';\nconst vm = require('vm');\n\nlet code =\n`(function(require) {\n\n const http = require('http');\n\n http.createServer( (request, response) => {\n response.writeHead(200, {'Content-Type': 'text/plain'});\n response.end('Hello World\\\\n');\n }).listen(8124);\n\n console.log('Server running at http://127.0.0.1:8124/');\n })`;\n\n vm.runInThisContext(code)(require);\n
\nNote: The require()
in the above case shares the state with the context it\nis passed from. This may introduce risks when untrusted code is executed, e.g.\naltering objects in the context in unwanted ways.
All JavaScript executed within Node.js runs within the scope of a "context".\nAccording to the V8 Embedder's Guide:
\n\n\nIn V8, a context is an execution environment that allows separate, unrelated,\nJavaScript applications to run in a single instance of V8. You must explicitly\nspecify the context in which you want any JavaScript code to be run.
\n
When the method vm.createContext()
is called, the sandbox
object that is\npassed in (or a newly created object if sandbox
is undefined
) is associated\ninternally with a new instance of a V8 Context. This V8 Context provides the\ncode
run using the vm
modules methods with an isolated global environment\nwithin which it can operate. The process of creating the V8 Context and\nassociating it with the sandbox
object is what this document refers to as\n"contextifying" the sandbox
.
The zlib
module provides compression functionality implemented using Gzip and\nDeflate/Inflate. It can be accessed using:
const zlib = require('zlib');\n
\nCompressing or decompressing a stream (such as a file) can be accomplished by\npiping the source stream data through a zlib
stream into a destination stream:
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
\nIt is also possible to compress or decompress data in a single step:
\nconst input = '.................................';\nzlib.deflate(input, (err, buffer) => {\n if (!err) {\n console.log(buffer.toString('base64'));\n } else {\n // handle error\n }\n});\n\nconst buffer = Buffer.from('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, (err, buffer) => {\n if (!err) {\n console.log(buffer.toString());\n } else {\n // handle error\n }\n});\n
\n",
"modules": [
{
"textRaw": "Compressing HTTP requests and responses",
"name": "compressing_http_requests_and_responses",
"desc": "The zlib
module can be used to implement support for the gzip
and deflate
\ncontent-encoding mechanisms defined by\nHTTP.
The HTTP Accept-Encoding
header is used within an http request to identify\nthe compression encodings accepted by the client. The Content-Encoding
\nheader is used to identify the compression encodings actually applied to a\nmessage.
Note: the examples given below are drastically simplified to show\nthe basic concept. Using zlib
encoding can be expensive, and the results\nought to be cached. See Memory Usage Tuning for more information\non the speed/memory/compression tradeoffs involved in zlib
usage.
// client request example\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nconst request = http.get({ host: 'example.com',\n path: '/',\n port: 80,\n headers: { 'Accept-Encoding': 'gzip,deflate' } });\nrequest.on('response', (response) => {\n var output = fs.createWriteStream('example.com_index.html');\n\n switch (response.headers['content-encoding']) {\n // or, just use zlib.createUnzip() to handle both cases\n case 'gzip':\n response.pipe(zlib.createGunzip()).pipe(output);\n break;\n case 'deflate':\n response.pipe(zlib.createInflate()).pipe(output);\n break;\n default:\n response.pipe(output);\n break;\n }\n});\n\n// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nconst zlib = require('zlib');\nconst http = require('http');\nconst fs = require('fs');\nhttp.createServer((request, response) => {\n 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
\nBy default, the zlib
methods will throw an error when decompressing\ntruncated data. However, if it is known that the data is incomplete, or\nthe desire is to inspect only the beginning of a compressed file, it is\npossible to suppress the default error handling by changing the flushing\nmethod that is used to compressed the last chunk of input data:
// This is a truncated version of the buffer from the above examples\nconst buffer = Buffer.from('eJzT0yMA', 'base64');\n\nzlib.unzip(buffer,\n {finishFlush: zlib.constants.Z_SYNC_FLUSH},\n (err, buffer) => {\n if (!err) {\n console.log(buffer.toString());\n } else {\n // handle error\n }\n});\n
\nThis will not change the behavior in other error-throwing situations, e.g.\nwhen the input data has an invalid format. Using this method, it will not be\npossible to determine whether the input ended prematurely or lacks the\nintegrity checks, making it necessary to manually check that the\ndecompressed result is valid.
\n", "type": "module", "displayName": "Compressing HTTP requests and responses" }, { "textRaw": "Flushing", "name": "flushing", "desc": "Calling .flush()
on a compression stream will make zlib
return as much\noutput as currently possible. This may come at the cost of degraded compression\nquality, but can be useful when data needs to be available as soon as possible.
In the following example, flush()
is used to write a compressed partial\nHTTP response to the client:
const zlib = require('zlib');\nconst http = require('http');\n\nhttp.createServer((request, response) => {\n // For the sake of simplicity, the Accept-Encoding checks are omitted.\n response.writeHead(200, { 'content-encoding': 'gzip' });\n const output = zlib.createGzip();\n output.pipe(response);\n\n setInterval(() => {\n output.write(`The current time is ${Date()}\\n`, () => {\n // The data has been passed to zlib, but the compression algorithm may\n // have decided to buffer the data for more efficient compression.\n // Calling .flush() will make the data available as soon as the client\n // is ready to receive it.\n output.flush();\n });\n }, 1000);\n}).listen(1337);\n
\n",
"type": "module",
"displayName": "Flushing"
}
],
"miscs": [
{
"textRaw": "Memory Usage Tuning",
"name": "Memory Usage Tuning",
"type": "misc",
"desc": "From zlib/zconf.h
, modified to node.js's usage:
The memory requirements for deflate are (in bytes):
\n(1 << (windowBits+2)) + (1 << (memLevel+9))\n
\nThat is: 128K for windowBits=15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.
\nFor example, to reduce the default memory requirements from 256K to 128K, the\noptions should be set to:
\n{ windowBits: 14, memLevel: 7 }\n
\nThis will, however, generally degrade compression.
\nThe memory requirements for inflate are (in bytes)
\n1 << windowBits\n
\nThat is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.
\nThis is in addition to a single internal output slab buffer of size\nchunkSize
, which defaults to 16K.
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.
In general, greater memory usage options will mean that Node.js has to make\nfewer calls to zlib
because it will be able to process more data on\neach write
operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.
All of the constants defined in zlib.h
are also defined on\nrequire('zlib').constants
. In the normal course of operations, it will not be\nnecessary to use these constants. They are documented so that their presence is\nnot surprising. This section is taken almost directly from the\nzlib documentation. See http://zlib.net/manual.html#Constants for more\ndetails.
Note: Previously, the constants were available directly from\nrequire('zlib')
, for instance zlib.Z_NO_FLUSH
. Accessing the constants\ndirectly from the module is currently still possible but should be considered\ndeprecated.
Allowed flush values.
\nzlib.constants.Z_NO_FLUSH
zlib.constants.Z_PARTIAL_FLUSH
zlib.constants.Z_SYNC_FLUSH
zlib.constants.Z_FULL_FLUSH
zlib.constants.Z_FINISH
zlib.constants.Z_BLOCK
zlib.constants.Z_TREES
Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.
\nzlib.constants.Z_OK
zlib.constants.Z_STREAM_END
zlib.constants.Z_NEED_DICT
zlib.constants.Z_ERRNO
zlib.constants.Z_STREAM_ERROR
zlib.constants.Z_DATA_ERROR
zlib.constants.Z_MEM_ERROR
zlib.constants.Z_BUF_ERROR
zlib.constants.Z_VERSION_ERROR
Compression levels.
\nzlib.constants.Z_NO_COMPRESSION
zlib.constants.Z_BEST_SPEED
zlib.constants.Z_BEST_COMPRESSION
zlib.constants.Z_DEFAULT_COMPRESSION
Compression strategy.
\nzlib.constants.Z_FILTERED
zlib.constants.Z_HUFFMAN_ONLY
zlib.constants.Z_RLE
zlib.constants.Z_FIXED
zlib.constants.Z_DEFAULT_STRATEGY
Each class takes an options
object. All options are optional.
Note that some options are only relevant when compressing, and are\nignored by the decompression classes.
\nflush
(default: zlib.constants.Z_NO_FLUSH
)finishFlush
(default: zlib.constants.Z_FINISH
)chunkSize
(default: 16*1024)windowBits
level
(compression only)memLevel
(compression only)strategy
(compression only)dictionary
(deflate/inflate only, empty dictionary by default)See the description of deflateInit2
and inflateInit2
at\nhttp://zlib.net/manual.html#Advanced for more information on these.
All of these take a Buffer or string as the first argument, an optional\nsecond argument to supply options to the zlib
classes and will call the\nsupplied callback with callback(error, result)
.
Every method has a *Sync
counterpart, which accept the same arguments, but\nwithout a callback.
Compress a Buffer or string with Deflate.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateSync(buf[, options])", "type": "method", "name": "deflateSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "Compress a Buffer or string with Deflate.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.deflateRaw(buf[, options], callback)", "type": "method", "name": "deflateRaw", "meta": { "added": [ "v0.6.0" ] }, "desc": "Compress a Buffer or string with DeflateRaw.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateRawSync(buf[, options])", "type": "method", "name": "deflateRawSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "Compress a Buffer or string with DeflateRaw.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.gunzip(buf[, options], callback)", "type": "method", "name": "gunzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "Decompress a Buffer or string with Gunzip.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gunzipSync(buf[, options])", "type": "method", "name": "gunzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "Decompress a Buffer or string with Gunzip.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.gzip(buf[, options], callback)", "type": "method", "name": "gzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "Compress a Buffer or string with Gzip.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gzipSync(buf[, options])", "type": "method", "name": "gzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "Compress a Buffer or string with Gzip.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.inflate(buf[, options], callback)", "type": "method", "name": "inflate", "meta": { "added": [ "v0.6.0" ] }, "desc": "Decompress a Buffer or string with Inflate.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateSync(buf[, options])", "type": "method", "name": "inflateSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "Decompress a Buffer or string with Inflate.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.inflateRaw(buf[, options], callback)", "type": "method", "name": "inflateRaw", "meta": { "added": [ "v0.6.0" ] }, "desc": "Decompress a Buffer or string with InflateRaw.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateRawSync(buf[, options])", "type": "method", "name": "inflateRawSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "Decompress a Buffer or string with InflateRaw.
\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.unzip(buf[, options], callback)", "type": "method", "name": "unzip", "meta": { "added": [ "v0.6.0" ] }, "desc": "Decompress a Buffer or string with Unzip.
\n\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.unzipSync(buf[, options])", "type": "method", "name": "unzipSync", "meta": { "added": [ "v0.11.12" ] }, "desc": "Decompress a Buffer or string with Unzip.
\n\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "options", "optional": true } ] } ] } ] } ], "meta": { "added": [ "v0.5.8" ] }, "classes": [ { "textRaw": "Class: zlib.Deflate", "type": "class", "name": "zlib.Deflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "Compress data using deflate.
\n" }, { "textRaw": "Class: zlib.DeflateRaw", "type": "class", "name": "zlib.DeflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "Compress data using deflate, and do not append a zlib
header.
Decompress a gzip stream.
\n" }, { "textRaw": "Class: zlib.Gzip", "type": "class", "name": "zlib.Gzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "Compress data using gzip.
\n" }, { "textRaw": "Class: zlib.Inflate", "type": "class", "name": "zlib.Inflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "Decompress a deflate stream.
\n" }, { "textRaw": "Class: zlib.InflateRaw", "type": "class", "name": "zlib.InflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "Decompress a raw deflate stream.
\n" }, { "textRaw": "Class: zlib.Unzip", "type": "class", "name": "zlib.Unzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.
\n" }, { "textRaw": "Class: zlib.Zlib", "type": "class", "name": "zlib.Zlib", "meta": { "added": [ "v0.5.8" ] }, "desc": "Not exported by the zlib
module. It is documented here because it is the base\nclass of the compressor/decompressor classes.
kind
defaults to zlib.constants.Z_FULL_FLUSH
.
Flush pending data. Don't call this frivolously, premature flushes negatively\nimpact the effectiveness of the compression algorithm.
\nCalling this only flushes data from the internal zlib
state, and does not\nperform flushing of any kind on the streams level. Rather, it behaves like a\nnormal call to .write()
, i.e. it will be queued up behind other pending\nwrites and will only produce output when data is being read from the stream.
Dynamically update the compression level and compression strategy.\nOnly applicable to deflate algorithm.
\n", "signatures": [ { "params": [ { "name": "level" }, { "name": "strategy" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.reset()", "type": "method", "name": "reset", "meta": { "added": [ "v0.7.0" ] }, "desc": "Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.
\n", "signatures": [ { "params": [] } ] } ] } ], "properties": [ { "textRaw": "zlib.constants", "name": "constants", "meta": { "added": [ "v7.0.0" ] }, "desc": "Provides an object enumerating Zlib-related constants.
\n" } ], "methods": [ { "textRaw": "zlib.createDeflate([options])", "type": "method", "name": "createDeflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "Returns a new Deflate object with an options.
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflateRaw([options])", "type": "method", "name": "createDeflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "Returns a new DeflateRaw object with an options.
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGunzip([options])", "type": "method", "name": "createGunzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "Returns a new Gunzip object with an options.
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGzip([options])", "type": "method", "name": "createGzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "Returns a new Gzip object with an options.
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflate([options])", "type": "method", "name": "createInflate", "meta": { "added": [ "v0.5.8" ] }, "desc": "Returns a new Inflate object with an options.
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflateRaw([options])", "type": "method", "name": "createInflateRaw", "meta": { "added": [ "v0.5.8" ] }, "desc": "Returns a new InflateRaw object with an options.
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createUnzip([options])", "type": "method", "name": "createUnzip", "meta": { "added": [ "v0.5.8" ] }, "desc": "Returns a new Unzip object with an options.
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] } ], "type": "module", "displayName": "Zlib" } ], "stability": 2, "stabilityText": "Stable", "properties": [ { "textRaw": "V8 Inspector Integration for Node.js", "name": "js", "desc": "NOTE: This is an experimental feature.
\nV8 Inspector integration allows attaching Chrome DevTools to Node.js\ninstances for debugging and profiling.
\nV8 Inspector can be enabled by passing the --inspect
flag when starting a\nNode.js application. It is also possible to supply a custom port with that flag,\ne.g. --inspect=9222
will accept DevTools connections on port 9222.
To break on the first line of the application code, provide the --debug-brk
\nflag in addition to --inspect
.
$ node --inspect index.js\nDebugger listening on port 9229.\nWarning: This is an experimental feature and could change at any time.\nTo start debugging, open the following URL in Chrome:\n chrome-devtools://devtools/remote/serve_file/@60cd6e859b9f557d2312f5bf532f6aec5f284980/inspector.html?experiments=true&v8only=true&ws=localhost:9229/node\n
\n\n\n"
}
],
"classes": [
{
"textRaw": "Class: Error",
"type": "class",
"name": "Error",
"desc": "A generic JavaScript Error
object that does not denote any specific\ncircumstance of why the error occurred. Error
objects capture a "stack trace"\ndetailing the point in the code at which the Error
was instantiated, and may\nprovide a text description of the error.
All errors generated by Node.js, including all System and JavaScript errors,\nwill either be instances of, or inherit from, the Error
class.
Creates a .stack
property on targetObject
, which when accessed returns\na string representing the location in the code at which\nError.captureStackTrace()
was called.
const myObject = {};\nError.captureStackTrace(myObject);\nmyObject.stack // similar to `new Error().stack`\n
\nThe first line of the trace, instead of being prefixed with ErrorType:\nmessage
, will be the result of calling targetObject.toString()
.
The optional constructorOpt
argument accepts a function. If given, all frames\nabove constructorOpt
, including constructorOpt
, will be omitted from the\ngenerated stack trace.
The constructorOpt
argument is useful for hiding implementation\ndetails of error generation from an end user. For instance:
function MyError() {\n Error.captureStackTrace(this, MyError);\n}\n\n// Without passing MyError to captureStackTrace, the MyError\n// frame would show up in the .stack property. By passing\n// the constructor, we omit that frame and all frames above it.\nnew MyError().stack\n
\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)
).
The default value is 10
but may be set to any valid JavaScript number. Changes\nwill affect any stack trace captured after the value has been changed.
If set to a non-number value, or set to a negative number, stack traces will\nnot capture any frames.
\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.
const err = new Error('The message');\nconsole.log(err.message);\n// Prints: The message\n
\n"
},
{
"textRaw": "error.stack",
"name": "stack",
"desc": "Returns a string describing the point in the code at which the Error
was\ninstantiated.
For example:
\nError: Things keep happening!\n at /home/gbusey/file.js:525:2\n at Frobnicator.refrobulate (/home/gbusey/business-logic.js:424:21)\n at Actor.<anonymous> (/home/gbusey/actors.js:400:8)\n at increaseSynergy (/home/gbusey/actors.js:701:6)\n
\nThe first line is formatted as <error class name>: <error message>
, and\nis followed by a series of stack frames (each line beginning with "at ").\nEach frame describes a call site within the code that lead to the error being\ngenerated. V8 attempts to display a name for each function (by variable name,\nfunction name, or object method name), but occasionally it will not be able to\nfind a suitable name. If V8 cannot determine a name for the function, only\nlocation information will be displayed for that frame. Otherwise, the\ndetermined function name will be displayed with location information appended\nin parentheses.
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:
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
\nThe location information will be one of:
\nnative
, if the frame represents a call internal to V8 (as in [].forEach
).plain-filename.js:line:column
, if the frame represents a call internal\n to Node.js./absolute/path/to/file.js:line:column
, if the frame represents a call in\na user program, or its dependencies.The string representing the stack trace is lazily generated when the\nerror.stack
property is accessed.
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.
System-level errors are generated as augmented Error
instances, which are\ndetailed here.
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.
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.
For example:
\nrequire('net').connect(-1);\n // throws RangeError, port should be > 0 && < 65536\n
\nNode.js will generate and throw RangeError
instances immediately as a form\nof argument validation.
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.
While client code may generate and propagate these errors, in practice, only V8\nwill do so.
\ndoesNotExist;\n // throws ReferenceError, doesNotExist is not a variable in this program.\n
\nReferenceError
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.
const assert = require('assert');\ntry {\n doesNotExist;\n} catch(err) {\n assert(err.arguments[0], 'doesNotExist');\n}\n
\nUnless an application is dynamically generating and running code,\nReferenceError
instances should always be considered a bug in the code\nor its dependencies.
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.
try {\n require('vm').runInThisContext('binary ! isNotOk');\n} catch(err) {\n // err will be a SyntaxError\n}\n
\nSyntaxError
instances are unrecoverable in the context that created them –\nthey may only be caught by other contexts.
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.
require('url').parse(() => { });\n // throws TypeError, since it expected a string\n
\nNode.js will generate and throw TypeError
instances immediately as a form\nof argument validation.
Used to handle binary data. See the buffer section.
\n" }, { "textRaw": "clearImmediate(immediateObject)", "type": "global", "name": "clearImmediate", "meta": { "added": [ "v0.9.1" ] }, "desc": "clearImmediate
is described in the timers section.
clearInterval
is described in the timers section.
clearTimeout
is described in the timers section.
Used to print to stdout and stderr. See the console
section.
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.
The process object. See the process
object section.
setImmediate
is described in the timers section.
setInterval
is described in the timers section.
setTimeout
is described in the timers section.
The process
object is a global
that provides information about, and control\nover, the current Node.js process. As a global, it is always available to\nNode.js applications without using require()
.
The process
object is an instance of EventEmitter
.
The 'beforeExit'
event is emitted when Node.js empties its event loop and has\nno additional work to schedule. Normally, the Node.js process will exit when\nthere is no work scheduled, but a listener registered on the 'beforeExit'
\nevent can make asynchronous calls, and thereby cause the Node.js process to\ncontinue.
The listener callback function is invoked with the value of\nprocess.exitCode
passed as the only argument.
The 'beforeExit'
event is not emitted for conditions causing explicit\ntermination, such as calling process.exit()
or uncaught exceptions.
The 'beforeExit'
should not be used as an alternative to the 'exit'
event\nunless the intention is to schedule additional work.
If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'disconnect'
event will be emitted when\nthe IPC channel is closed.
The 'exit'
event is emitted when the Node.js process is about to exit as a\nresult of either:
process.exit()
method being called explicitly;There is no way to prevent the exiting of the event loop at this point, and once\nall 'exit'
listeners have finished running the Node.js process will terminate.
The listener callback function is invoked with the exit code specified either\nby the process.exitCode
property, or the exitCode
argument passed to the\nprocess.exit()
method, as the only argument.
For example:
\nprocess.on('exit', (code) => {\n console.log(`About to exit with code: ${code}`);\n});\n
\nListener functions must only perform synchronous operations. The Node.js\nprocess will exit immediately after calling the 'exit'
event listeners\ncausing any additional work still queued in the event loop to be abandoned.\nIn the following example, for instance, the timeout will never occur:
process.on('exit', (code) => {\n setTimeout(() => {\n console.log('This will not run');\n }, 0);\n});\n
\n",
"params": []
},
{
"textRaw": "Event: 'message'",
"type": "event",
"name": "message",
"meta": {
"added": [
"v0.5.10"
]
},
"desc": "If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the 'message'
event is emitted whenever a\nmessage sent by a parent process using childprocess.send()
is received by\nthe child process.
The listener callback is invoked with the following arguments:
\nmessage
{Object} a parsed JSON object or primitive valuesendHandle
{Handle object} a net.Socket
or net.Server
object, or\nundefined.The 'rejectionHandled'
event is emitted whenever a Promise
has been rejected\nand an error handler was attached to it (using promise.catch()
, for\nexample) later than one turn of the Node.js event loop.
The listener callback is invoked with a reference to the rejected Promise
as\nthe only argument.
The Promise
object would have previously been emitted in an\n'unhandledRejection'
event, but during the course of processing gained a\nrejection handler.
There is no notion of a top level for a Promise
chain at which rejections can\nalways be handled. Being inherently asynchronous in nature, a Promise
\nrejection can be handled at a future point in time — possibly much later than\nthe event loop turn it takes for the 'unhandledRejection'
event to be emitted.
Another way of stating this is that, unlike in synchronous code where there is\nan ever-growing list of unhandled exceptions, with Promises there can be a\ngrowing-and-shrinking list of unhandled rejections.
\nIn synchronous code, the 'uncaughtException'
event is emitted when the list of\nunhandled exceptions grows.
In asynchronous code, the 'unhandledRejection'
event is emitted when the list\nof unhandled rejections grows, and the 'rejectionHandled'
event is emitted\nwhen the list of unhandled rejections shrinks.
For example:
\nconst unhandledRejections = new Map();\nprocess.on('unhandledRejection', (reason, p) => {\n unhandledRejections.set(p, reason);\n});\nprocess.on('rejectionHandled', (p) => {\n unhandledRejections.delete(p);\n});\n
\nIn this example, the unhandledRejections
Map
will grow and shrink over time,\nreflecting rejections that start unhandled and then become handled. It is\npossible to record such errors in an error log, either periodically (which is\nlikely best for long-running application) or upon process exit (which is likely\nmost convenient for scripts).
The 'uncaughtException'
event is emitted when an uncaught JavaScript\nexception bubbles all the way back to the event loop. By default, Node.js\nhandles such exceptions by printing the stack trace to stderr
and exiting.\nAdding a handler for the 'uncaughtException'
event overrides this default\nbehavior.
The listener function is called with the Error
object passed as the only\nargument.
For example:
\nprocess.on('uncaughtException', (err) => {\n fs.writeSync(1, `Caught exception: ${err}`);\n});\n\nsetTimeout(() => {\n console.log('This will still run.');\n}, 500);\n\n// Intentionally cause an exception, but don't catch it.\nnonexistentFunc();\nconsole.log('This will not run.');\n
\n",
"modules": [
{
"textRaw": "Warning: Using `'uncaughtException'` correctly",
"name": "warning:_using_`'uncaughtexception'`_correctly",
"desc": "Note that 'uncaughtException'
is a crude mechanism for exception handling\nintended to be used only as a last resort. The event should not be used as\nan equivalent to On Error Resume Next
. Unhandled exceptions inherently mean\nthat an application is in an undefined state. Attempting to resume application\ncode without properly recovering from the exception can cause additional\nunforeseen and unpredictable issues.
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.
\nAttempting 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.
\nThe 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'
.
To restart a crashed application in a more reliable way, whether uncaughtException
\nis emitted or not, an external monitor should be employed in a separate process\nto detect application failures and recover or restart as needed.
The 'unhandledRejection
' event is emitted whenever a Promise
is rejected and\nno error handler is attached to the promise within a turn of the event loop.\nWhen programming with Promises, exceptions are encapsulated as "rejected\npromises". Rejections can be caught and handled using promise.catch()
and\nare propagated through a Promise
chain. The 'unhandledRejection'
event is\nuseful for detecting and keeping track of promises that were rejected whose\nrejections have not yet been handled.
The listener function is called with the following arguments:
\nreason
{Error|any} The object with which the promise was rejected\n(typically an Error
object).p
the Promise
that was rejected.For example:
\nprocess.on('unhandledRejection', (reason, p) => {\n console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);\n // application specific logging, throwing an error, or other logic here\n});\n\nsomePromise.then((res) => {\n return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)\n}); // no `.catch` or `.then`\n
\nThe following will also trigger the 'unhandledRejection'
event to be\nemitted:
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
\nIn this example case, it is possible to track the rejection as a developer error\nas would typically be the case for other 'unhandledRejection'
events. To\naddress such failures, a non-operational\n.catch(() => { })
handler may be attached to\nresource.loaded
, which would prevent the 'unhandledRejection'
event from\nbeing emitted. Alternatively, the 'rejectionHandled'
event may be used.
The 'warning'
event is emitted whenever Node.js emits a process warning.
A process warning is similar to an error in that it describes exceptional\nconditions that are being brought to the user's attention. However, warnings\nare not part of the normal Node.js and JavaScript error handling flow.\nNode.js can emit warnings whenever it detects bad coding practices that could\nlead to sub-optimal application performance, bugs or security vulnerabilities.
\nThe listener function is called with a single warning
argument whose value is\nan Error
object. There are three key properties that describe the warning:
name
{String} The name of the warning (currently Warning
by default).message
{String} A system-provided description of the warning.stack
{String} A stack trace to the location in the code where the warning\nwas issued.process.on('warning', (warning) => {\n console.warn(warning.name); // Print the warning name\n console.warn(warning.message); // Print the warning message\n console.warn(warning.stack); // Print the stack trace\n});\n
\nBy default, Node.js will print process warnings to stderr
. The --no-warnings
\ncommand-line option can be used to suppress the default console output but the\n'warning'
event will still be emitted by the process
object.
The following example illustrates the warning that is printed to stderr
when\ntoo many listeners have been added to an event
$ node\n> event.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> (node:38638) Warning: Possible EventEmitter memory leak detected. 2 foo\n... listeners added. Use emitter.setMaxListeners() to increase limit\n
\nIn contrast, the following example turns off the default warning output and\nadds a custom handler to the 'warning'
event:
$ node --no-warnings\n> var p = process.on('warning', (warning) => console.warn('Do not do that!'));\n> event.defaultMaxListeners = 1;\n> process.on('foo', () => {});\n> process.on('foo', () => {});\n> Do not do that!\n
\nThe --trace-warnings
command-line option can be used to have the default\nconsole output for warnings include the full stack trace of the warning.
Launching Node.js using the --throw-deprecation
command line flag will\ncause custom deprecation warnings to be thrown as exceptions.
Using the --trace-deprecation
command line flag will cause the custom\ndeprecation to be printed to stderr
along with the stack trace.
Using the --no-deprecation
command line flag will suppress all reporting\nof the custom deprecation.
The *-deprecation
command line flags only affect warnings that use the name\nDeprecationWarning
.
See the process.emitWarning()
method for issuing\ncustom or application-specific warnings.
Signal events will be emitted when the Node.js process receives a signal. Please\nrefer to signal(7) for a listing of standard POSIX signal names such as\nSIGINT
, SIGHUP
, etc.
The name of each event will be the uppercase common name for the signal (e.g.\n'SIGINT'
for SIGINT
signals).
For example:
\n// Begin reading from stdin so the process does not exit.\nprocess.stdin.resume();\n\nprocess.on('SIGINT', () => {\n console.log('Received SIGINT. Press Control-D to exit.');\n});\n
\nNote: An easy way to send the SIGINT
signal is with <Ctrl>-C
in most\nterminal programs.
It is important to take note of the following:
\nSIGUSR1
is reserved by Node.js to start the debugger. It's possible to\ninstall a listener but doing so will not stop the debugger from starting.SIGTERM
and SIGINT
have default handlers on non-Windows platforms that\nresets the terminal mode before exiting with code 128 + signal number
. If\none of these signals has a listener installed, its default behavior will be\nremoved (Node.js will no longer exit).SIGPIPE
is ignored by default. It can have a listener installed.SIGHUP
is generated on Windows when the console window is closed, and on\nother platforms under various similar conditions, see signal(7). It can have a\nlistener installed, however Node.js will be unconditionally terminated by\nWindows about 10 seconds later. On non-Windows platforms, the default\nbehavior of SIGHUP
is to terminate Node.js, but once a listener has been\ninstalled its default behavior will be removed.SIGTERM
is not supported on Windows, it can be listened on.SIGINT
from the terminal is supported on all platforms, and can usually be\ngenerated with CTRL+C
(though this may be configurable). It is not generated\nwhen terminal raw mode is enabled.SIGBREAK
is delivered on Windows when <Ctrl>+<Break>
is pressed, on\nnon-Windows platforms it can be listened on, but there is no way to send or\ngenerate it.SIGWINCH
is delivered when the console has been resized. On Windows, this\nwill only happen on write to the console when the cursor is being moved, or\nwhen a readable tty is used in raw mode.SIGKILL
cannot have a listener installed, it will unconditionally terminate\nNode.js on all platforms.SIGSTOP
cannot have a listener installed.SIGBUS
, SIGFPE
, SIGSEGV
and SIGILL
, when not raised artificially\n using kill(2), inherently leave the process in a state from which it is not\n safe to attempt to call JS listeners. Doing so might lead to the process\n hanging in an endless loop, since listeners attached using process.on()
are\n called asynchronously and therefore unable to correct the underlying problem.Note: Windows does not support sending signals, but Node.js offers some\nemulation with process.kill()
, and ChildProcess.kill()
. Sending\nsignal 0
can be used to test for the existence of a process. Sending SIGINT
,\nSIGTERM
, and SIGKILL
cause the unconditional termination of the target\nprocess.
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:
1
Uncaught Fatal Exception - There was an uncaught exception,\nand it was not handled by a domain or an 'uncaughtException'
event\nhandler.2
- Unused (reserved by Bash for builtin misuse)3
Internal JavaScript Parse Error - The JavaScript source code\ninternal in Node.js's bootstrapping process caused a parse error. This\nis extremely rare, and generally can only happen during development\nof Node.js itself.4
Internal JavaScript Evaluation Failure - The JavaScript\nsource code internal in Node.js's bootstrapping process failed to\nreturn a function value when evaluated. This is extremely rare, and\ngenerally can only happen during development of Node.js itself.5
Fatal Error - There was a fatal unrecoverable error in V8.\nTypically a message will be printed to stderr with the prefix FATAL\nERROR
.6
Non-function Internal Exception Handler - There was an\nuncaught exception, but the internal fatal exception handler\nfunction was somehow set to a non-function, and could not be called.7
Internal Exception Handler Run-Time Failure - There was an\nuncaught exception, and the internal fatal exception handler\nfunction itself threw an error while attempting to handle it. This\ncan happen, for example, if a 'uncaughtException'
or\ndomain.on('error')
handler throws an error.8
- Unused. In previous versions of Node.js, exit code 8 sometimes\nindicated an uncaught exception.9
- Invalid Argument - Either an unknown option was specified,\nor an option requiring a value was provided without a value.10
Internal JavaScript Run-Time Failure - The JavaScript\nsource code internal in Node.js's bootstrapping process threw an error\nwhen the bootstrapping function was called. This is extremely rare,\nand generally can only happen during development of Node.js itself.12
Invalid Debug Argument - The --debug
, --inspect
and/or\n--debug-brk
options were set, but the port number chosen was invalid\nor unavailable.>128
Signal Exits - If Node.js receives a fatal signal such as\nSIGKILL
or SIGHUP
, then its exit code will be 128
plus the\nvalue of the signal code. This is a standard Unix practice, since\nexit codes are defined to be 7-bit integers, and signal exits set\nthe high-order bit, and then contain the value of the signal code.The process.abort()
method causes the Node.js process to exit immediately and\ngenerate a core file.
The process.chdir()
method changes the current working directory of the\nNode.js process or throws an exception if doing so fails (for instance, if\nthe specified directory
does not exist).
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
\n"
},
{
"textRaw": "process.cpuUsage([previousValue])",
"type": "method",
"name": "cpuUsage",
"meta": {
"added": [
"v6.1.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Object} ",
"options": [
{
"textRaw": "`user` {Integer} ",
"name": "user",
"type": "Integer"
},
{
"textRaw": "`system` {Integer} ",
"name": "system",
"type": "Integer"
}
],
"name": "return",
"type": "Object"
},
"params": [
{
"textRaw": "`previousValue` {Object} A previous return value from calling `process.cpuUsage()` ",
"name": "previousValue",
"type": "Object",
"desc": "A previous return value from calling `process.cpuUsage()`",
"optional": true
}
]
},
{
"params": [
{
"name": "previousValue",
"optional": true
}
]
}
],
"desc": "The process.cpuUsage()
method returns the user and system CPU time usage of\nthe current process, in an object with properties user
and system
, whose\nvalues are microsecond values (millionth of a second). These values measure time\nspent in user and system code respectively, and may end up being greater than\nactual elapsed time if multiple CPU cores are performing work for this process.
The result of a previous call to process.cpuUsage()
can be passed as the\nargument to the function, to get a diff reading.
const startUsage = process.cpuUsage();\n// { user: 38579, system: 6986 }\n\n// spin the CPU for 500 milliseconds\nconst now = Date.now();\nwhile (Date.now() - now < 500);\n\nconsole.log(process.cpuUsage(startUsage));\n// { user: 514883, system: 11226 }\n
\n"
},
{
"textRaw": "process.cwd()",
"type": "method",
"name": "cwd",
"meta": {
"added": [
"v0.1.8"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {String} ",
"name": "return",
"type": "String"
},
"params": []
},
{
"params": []
}
],
"desc": "The process.cwd()
method returns the current working directory of the Node.js\nprocess.
console.log(`Current directory: ${process.cwd()}`);\n
\n"
},
{
"textRaw": "process.disconnect()",
"type": "method",
"name": "disconnect",
"meta": {
"added": [
"v0.7.2"
]
},
"desc": "If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.disconnect()
method will close the\nIPC channel to the parent process, allowing the child process to exit gracefully\nonce there are no other connections keeping it alive.
The effect of calling process.disconnect()
is that same as calling the parent\nprocess's ChildProcess.disconnect()
.
If the Node.js process was not spawned with an IPC channel,\nprocess.disconnect()
will be undefined
.
The process.emitWarning()
method can be used to emit custom or application\nspecific process warnings. These can be listened for by adding a handler to the\nprocess.on('warning')
event.
// Emit a warning using a string...\nprocess.emitWarning('Something happened!');\n// Emits: (node: 56338) Warning: Something happened!\n
\n// Emit a warning using a string and a name...\nprocess.emitWarning('Something Happened!', 'CustomWarning');\n// Emits: (node:56338) CustomWarning: Something Happened!\n
\nIn each of the previous examples, an Error
object is generated internally by\nprocess.emitWarning()
and passed through to the\nprocess.on('warning')
event.
process.on('warning', (warning) => {\n console.warn(warning.name);\n console.warn(warning.message);\n console.warn(warning.stack);\n});\n
\nIf warning
is passed as an Error
object, it will be passed through to the\nprocess.on('warning')
event handler unmodified (and the optional name
\nand ctor
arguments will be ignored):
// Emit a warning using an Error object...\nconst myWarning = new Error('Warning! Something happened!');\nmyWarning.name = 'CustomWarning';\n\nprocess.emitWarning(myWarning);\n// Emits: (node:56338) CustomWarning: Warning! Something Happened!\n
\nA TypeError
is thrown if warning
is anything other than a string or Error
\nobject.
Note that while process warnings use Error
objects, the process warning\nmechanism is not a replacement for normal error handling mechanisms.
The following additional handling is implemented if the warning name
is\nDeprecationWarning
:
--throw-deprecation
command-line flag is used, the deprecation\nwarning is thrown as an exception rather than being emitted as an event.--no-deprecation
command-line flag is used, the deprecation\nwarning is suppressed.--trace-deprecation
command-line flag is used, the deprecation\nwarning is printed to stderr
along with the full stack trace.As a best practice, warnings should be emitted only once per process. To do\nso, it is recommended to place the emitWarning()
behind a simple boolean\nflag as illustrated in the example below:
function emitMyWarning() {\n if (!emitMyWarning.warned) {\n emitMyWarning.warned = true;\n process.emitWarning('Only warn once!');\n }\n}\nemitMyWarning();\n// Emits: (node: 56339) Warning: Only warn once!\nemitMyWarning();\n// Emits nothing\n
\n",
"type": "module",
"displayName": "Avoiding duplicate warnings"
}
]
},
{
"textRaw": "process.exit([code])",
"type": "method",
"name": "exit",
"meta": {
"added": [
"v0.1.13"
]
},
"signatures": [
{
"params": [
{
"textRaw": "`code` {Integer} The exit code. Defaults to `0`. ",
"name": "code",
"type": "Integer",
"desc": "The exit code. Defaults to `0`.",
"optional": true
}
]
},
{
"params": [
{
"name": "code",
"optional": true
}
]
}
],
"desc": "The process.exit()
method instructs Node.js to terminate the process as\nquickly as possible with the specified exit code
. If the code
is omitted,\nexit uses either the 'success' code 0
or the value of process.exitCode
if\nspecified.
To exit with a 'failure' code:
\nprocess.exit(1);\n
\nThe shell that executed Node.js should see the exit code as 1
.
It is important to note that calling process.exit()
will force the process to\nexit as quickly as possible even if there are still asynchronous operations\npending that have not yet completed fully, including I/O operations to\nprocess.stdout
and process.stderr
.
In most situations, it is not actually necessary to call process.exit()
\nexplicitly. The Node.js process will exit on its own if there is no additional\nwork pending in the event loop. The process.exitCode
property can be set to\ntell the process which exit code to use when the process exits gracefully.
For instance, the following example illustrates a misuse of the\nprocess.exit()
method that could lead to data printed to stdout being\ntruncated and lost:
// This is an example of what *not* to do:\nif (someConditionNotMet()) {\n printUsageToStdout();\n process.exit(1);\n}\n
\nThe reason this is problematic is because writes to process.stdout
in Node.js\nare sometimes non-blocking and may occur over multiple ticks of the Node.js\nevent loop. Calling process.exit()
, however, forces the process to exit\nbefore those additional writes to stdout
can be performed.
Rather than calling process.exit()
directly, the code should set the\nprocess.exitCode
and allow the process to exit naturally by avoiding\nscheduling any additional work for the event loop:
// How to properly set the exit code while letting\n// the process exit gracefully.\nif (someConditionNotMet()) {\n printUsageToStdout();\n process.exitCode = 1;\n}\n
\nIf it is necessary to terminate the Node.js process due to an error condition,\nthrowing an uncaught error and allowing the process to terminate accordingly\nis safer than calling process.exit()
.
The process.getegid()
method returns the numerical effective group identity\nof the Node.js process. (See getegid(2).)
if (process.getegid) {\n console.log(`Current gid: ${process.getegid()}`);\n}\n
\nNote: This function is only available on POSIX platforms (i.e. not Windows\nor Android)
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.geteuid()", "type": "method", "name": "geteuid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "The process.geteuid()
method returns the numerical effective user identity of\nthe process. (See geteuid(2).)
if (process.geteuid) {\n console.log(`Current uid: ${process.geteuid()}`);\n}\n
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.getgid()", "type": "method", "name": "getgid", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object} ", "name": "return", "type": "Object" }, "params": [] }, { "params": [] } ], "desc": "The process.getgid()
method returns the numerical group identity of the\nprocess. (See getgid(2).)
if (process.getgid) {\n console.log(`Current gid: ${process.getgid()}`);\n}\n
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Array} ", "name": "return", "type": "Array" }, "params": [] }, { "params": [] } ], "desc": "The process.getgroups()
method returns an array with the supplementary group\nIDs. POSIX leaves it unspecified if the effective group ID is included but\nNode.js ensures it always is.
Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "meta": { "added": [ "v0.1.28" ] }, "signatures": [ { "return": { "textRaw": "Returns: {Integer} ", "name": "return", "type": "Integer" }, "params": [] }, { "params": [] } ], "desc": "The process.getuid()
method returns the numeric user identity of the process.\n(See getuid(2).)
if (process.getuid) {\n console.log(`Current uid: ${process.getuid()}`);\n}\n
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.hrtime([time])", "type": "method", "name": "hrtime", "meta": { "added": [ "v0.7.6" ] }, "desc": "The process.hrtime()
method returns the current high-resolution real time in a\n[seconds, nanoseconds]
tuple Array. time
is an optional parameter that must\nbe the result of a previous process.hrtime()
call (and therefore, a real time\nin a [seconds, nanoseconds]
tuple Array containing a previous time) to diff\nwith the current time. These times are relative to an arbitrary time in the\npast, and not related to the time of day and therefore not subject to clock\ndrift. The primary use is for measuring performance between intervals.
Passing in the result of a previous call to process.hrtime()
is useful for\ncalculating an amount of time passed between calls:
var time = process.hrtime();\n// [ 1800216, 25 ]\n\nsetTimeout(() => {\n var diff = process.hrtime(time);\n // [ 1, 552 ]\n\n console.log(`Benchmark took ${diff[0] * 1e9 + diff[1]} nanoseconds`);\n // benchmark took 1000000527 nanoseconds\n}, 1000);\n
\nConstructing an array by some method other than calling process.hrtime()
and\npassing the result to process.hrtime() will result in undefined behavior.
The process.initgroups()
method reads the /etc/group
file and initializes\nthe group access list, using all groups of which the user is a member. This is\na privileged operation that requires that the Node.js process either have root
\naccess or the CAP_SETGID
capability.
Note that care must be taken when dropping privileges. Example:
\nconsole.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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.kill(pid[, signal])", "type": "method", "name": "kill", "meta": { "added": [ "v0.0.6" ] }, "signatures": [ { "params": [ { "textRaw": "`pid` {number} A process ID ", "name": "pid", "type": "number", "desc": "A process ID" }, { "textRaw": "`signal` {String|number} The signal to send, either as a string or number. Defaults to `'SIGTERM'`. ", "name": "signal", "type": "String|number", "desc": "The signal to send, either as a string or number. Defaults to `'SIGTERM'`.", "optional": true } ] }, { "params": [ { "name": "pid" }, { "name": "signal", "optional": true } ] } ], "desc": "The process.kill()
method sends the signal
to the process identified by\npid
.
Signal names are strings such as 'SIGINT'
or 'SIGHUP'
. See Signal Events\nand kill(2) for more information.
This method will throw an error if the target pid
does not exist. As a special\ncase, a signal of 0
can be used to test for the existence of a process.\nWindows platforms will throw an error if the pid
is used to kill a process\ngroup.
Note:Even though the name of this function is process.kill()
, it is really\njust a signal sender, like the kill
system call. The signal sent may do\nsomething other than kill the target process.
For example:
\nprocess.on('SIGHUP', () => {\n console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(() => {\n console.log('Exiting.');\n process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');\n
\nNote: When SIGUSR1
is received by a Node.js process, Node.js will start the\ndebugger, see Signal Events.
The process.memoryUsage()
method returns an object describing the memory usage\nof the Node.js process measured in bytes.
For example, the code:
\nconsole.log(process.memoryUsage());\n
\nWill generate:
\n{\n rss: 4935680,\n heapTotal: 1826816,\n heapUsed: 650472,\n external: 49879\n}\n
\nheapTotal
and heapUsed
refer to V8's memory usage.\nexternal
refers to the memory usage of C++ objects bound to JavaScript\nobjects managed by V8.
The process.nextTick()
method adds the callback
to the "next tick queue".\nOnce the current turn of the event loop turn runs to completion, all callbacks\ncurrently in the next tick queue will be called.
This is not a simple alias to setTimeout(fn, 0)
. It is much more\nefficient. It runs before any additional I/O events (including\ntimers) fire in subsequent ticks of the event loop.
console.log('start');\nprocess.nextTick(() => {\n console.log('nextTick callback');\n});\nconsole.log('scheduled');\n// Output:\n// start\n// scheduled\n// nextTick callback\n
\nThis is important when developing APIs in order to give users the opportunity\nto assign event handlers after an object has been constructed but before any\nI/O has occurred:
\nfunction 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
\nIt is very important for APIs to be either 100% synchronous or 100%\nasynchronous. Consider this example:
\n// WARNING! DO NOT USE! BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n if (arg) {\n cb();\n return;\n }\n\n fs.stat('file', cb);\n}\n
\nThis API is hazardous because in the following case:
\nmaybeSync(true, () => {\n foo();\n});\nbar();\n
\nIt is not clear whether foo()
or bar()
will be called first.
The following approach is much better:
\nfunction definitelyAsync(arg, cb) {\n if (arg) {\n process.nextTick(cb);\n return;\n }\n\n fs.stat('file', cb);\n}\n
\nNote: the next tick queue is completely drained on each pass of the\nevent loop before additional I/O is processed. As a result,\nrecursively setting nextTick callbacks will block any I/O from\nhappening, just like a while(true);
loop.
If Node.js is spawned with an IPC channel, the process.send()
method can be\nused to send messages to the parent process. Messages will be received as a\n'message'
event on the parent's ChildProcess
object.
If Node.js was not spawned with an IPC channel, process.send()
will be\nundefined
.
Note: This function uses JSON.stringify()
internally to serialize the\nmessage
.*
The process.setegid()
method sets the effective group identity of the process.\n(See setegid(2).) The id
can be passed as either a numeric ID or a group\nname string. If a group name is specified, this method blocks while resolving\nthe associated a numeric ID.
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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.seteuid(id)", "type": "method", "name": "seteuid", "meta": { "added": [ "v2.0.0" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {String|number} A user name or ID ", "name": "id", "type": "String|number", "desc": "A user name or ID" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "The process.seteuid()
method sets the effective user identity of the process.\n(See seteuid(2).) The id
can be passed as either a numeric ID or a username\nstring. If a username is specified, the method blocks while resolving the\nassociated numeric ID.
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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "meta": { "added": [ "v0.1.31" ] }, "signatures": [ { "params": [ { "textRaw": "`id` {String|number} The group name or ID ", "name": "id", "type": "String|number", "desc": "The group name or ID" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "The process.setgid()
method sets the group identity of the process. (See\nsetgid(2).) The id
can be passed as either a numeric ID or a group name\nstring. If a group name is specified, this method blocks while resolving the\nassociated numeric ID.
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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.setgroups(groups)", "type": "method", "name": "setgroups", "meta": { "added": [ "v0.9.4" ] }, "signatures": [ { "params": [ { "textRaw": "`groups` {Array} ", "name": "groups", "type": "Array" } ] }, { "params": [ { "name": "groups" } ] } ], "desc": "The process.setgroups()
method sets the supplementary group IDs for the\nNode.js process. This is a privileged operation that requires the Node.js process\nto have root
or the CAP_SETGID
capability.
The groups
array can contain numeric group IDs, group names or both.
Note: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n" }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "meta": { "added": [ "v0.1.28" ] }, "desc": "The process.setuid(id)
method sets the user identity of the process. (See\nsetuid(2).) The id
can be passed as either a numeric ID or a username string.\nIf a username is specified, the method blocks while resolving the associated\nnumeric ID.
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
\nNote: This function is only available on POSIX platforms (i.e. not Windows or\nAndroid)
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "meta": { "added": [ "v0.1.19" ] }, "signatures": [ { "params": [ { "textRaw": "`mask` {number} ", "name": "mask", "type": "number", "optional": true } ] }, { "params": [ { "name": "mask", "optional": true } ] } ], "desc": "The process.umask()
method sets or returns the Node.js process's file mode\ncreation mask. Child processes inherit the mask from the parent process. The old\nmask is return if the mask
argument is given, otherwise returns the current\nmask.
const newmask = 0o022;\nconst oldmask = process.umask(newmask);\nconsole.log(\n `Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`\n);\n
\n"
},
{
"textRaw": "process.uptime()",
"type": "method",
"name": "uptime",
"meta": {
"added": [
"v0.5.0"
]
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Number} ",
"name": "return",
"type": "Number"
},
"params": []
},
{
"params": []
}
],
"desc": "The process.uptime()
method returns the number of seconds the current Node.js\nprocess has been running.
The process.arch
property returns a String identifying the processor\narchitecture that the Node.js process is currently running on. For instance\n'arm'
, 'ia32'
, or 'x64'
.
console.log(`This processor architecture is ${process.arch}`);\n
\n"
},
{
"textRaw": "`argv` {Array} ",
"type": "Array",
"name": "argv",
"meta": {
"added": [
"v0.1.27"
]
},
"desc": "The process.argv
property returns an array containing the command line\narguments passed when the Node.js process was launched. The first element will\nbe process.execPath
. See process.argv0
if access to the original value of\nargv[0]
is needed. The second element will be the path to the JavaScript\nfile being executed. The remaining elements will be any additional command line\narguments.
For example, assuming the following script for process-args.js
:
// print process.argv\nprocess.argv.forEach((val, index) => {\n console.log(`${index}: ${val}`);\n});\n
\nLaunching the Node.js process as:
\n$ node process-2.js one two=three four\n
\nWould generate the output:
\n0: /usr/local/bin/node\n1: /Users/mjr/work/node/process-2.js\n2: one\n3: two=three\n4: four\n
\n"
},
{
"textRaw": "`argv0` {String} ",
"type": "String",
"name": "argv0",
"meta": {
"added": [
"6.4.0"
]
},
"desc": "The process.argv0
property stores a read-only copy of the original value of\nargv[0]
passed when Node.js starts.
$ bash -c 'exec -a customArgv0 ./node'\n> process.argv[0]\n'/Volumes/code/external/node/out/Release/node'\n> process.argv0\n'customArgv0'\n
\n"
},
{
"textRaw": "process.channel",
"name": "channel",
"meta": {
"added": [
"v7.1.0"
]
},
"desc": "If the Node.js process was spawned with an IPC channel (see the\nChild Process documentation), the process.channel
\nproperty is a reference to the IPC channel. If no IPC channel exists, this\nproperty is undefined
.
The process.config
property returns an Object containing the JavaScript\nrepresentation of the configure options used to compile the current Node.js\nexecutable. This is the same as the config.gypi
file that was produced when\nrunning the ./configure
script.
An example of the possible output looks like:
\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
\nNote: The process.config
property is not read-only and there are\nexisting modules in the ecosystem that are known to extend, modify, or entirely\nreplace the value of process.config
.
If the Node.js process is spawned with an IPC channel (see the Child Process\nand Cluster documentation), the process.connected
property will return\ntrue
so long as the IPC channel is connected and will return false
after\nprocess.disconnect()
is called.
Once process.connected
is false
, it is no longer possible to send messages\nover the IPC channel using process.send()
.
The process.env
property returns an object containing the user environment.\nSee environ(7).
An example of this object looks like:
\n{\n TERM: 'xterm-256color',\n SHELL: '/usr/local/bin/bash',\n USER: 'maciej',\n PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',\n PWD: '/Users/maciej',\n EDITOR: 'vim',\n SHLVL: '1',\n HOME: '/Users/maciej',\n LOGNAME: 'maciej',\n _: '/usr/local/bin/node'\n}\n
\nIt is possible to modify this object, but such modifications will not be\nreflected outside the Node.js process. In other words, the following example\nwould not work:
\n$ node -e 'process.env.foo = "bar"' && echo $foo\n
\nWhile the following will:
\nprocess.env.foo = 'bar';\nconsole.log(process.env.foo);\n
\nAssigning a property on process.env
will implicitly convert the value\nto a string.
Example:
\nprocess.env.test = null;\nconsole.log(process.env.test);\n// => 'null'\nprocess.env.test = undefined;\nconsole.log(process.env.test);\n// => 'undefined'\n
\nUse delete
to delete a property from process.env
.
Example:
\nprocess.env.TEST = 1;\ndelete process.env.TEST;\nconsole.log(process.env.TEST);\n// => undefined\n
\nOn Windows operating systems, environment variables are case-insensitive.
\nExample:
\nprocess.env.TEST = 1;\nconsole.log(process.env.test);\n// => 1\n
\n"
},
{
"textRaw": "`execArgv` {Object} ",
"type": "Object",
"name": "execArgv",
"meta": {
"added": [
"v0.7.7"
]
},
"desc": "The process.execArgv
property returns the set of Node.js-specific command-line\noptions passed when the Node.js process was launched. These options do not\nappear in the array returned by the process.argv
property, and do not\ninclude the Node.js executable, the name of the script, or any options following\nthe script name. These options are useful in order to spawn child processes with\nthe same execution environment as the parent.
For example:
\n$ node --harmony script.js --version\n
\nResults in process.execArgv
:
['--harmony']\n
\nAnd process.argv
:
['/usr/local/bin/node', 'script.js', '--version']\n
\n"
},
{
"textRaw": "`execPath` {String} ",
"type": "String",
"name": "execPath",
"meta": {
"added": [
"v0.1.100"
]
},
"desc": "The process.execPath
property returns the absolute pathname of the executable\nthat started the Node.js process.
For example:
\n'/usr/local/bin/node'\n
\n"
},
{
"textRaw": "`exitCode` {Integer} ",
"type": "Integer",
"name": "exitCode",
"meta": {
"added": [
"v0.11.8"
]
},
"desc": "A number which will be the process exit code, when the process either\nexits gracefully, or is exited via process.exit()
without specifying\na code.
Specifying a code to process.exit(code)
will override any\nprevious setting of process.exitCode
.
The process.mainModule
property provides an alternative way of retrieving\nrequire.main
. The difference is that if the main module changes at\nruntime, require.main
may still refer to the original main module in\nmodules that were required before the change occurred. Generally, it's\nsafe to assume that the two refer to the same module.
As with require.main
, process.mainModule
will be undefined
if there\nis no entry script.
The process.pid
property returns the PID of the process.
console.log(`This process is pid ${process.pid}`);\n
\n"
},
{
"textRaw": "`platform` {String} ",
"type": "String",
"name": "platform",
"meta": {
"added": [
"v0.1.16"
]
},
"desc": "The process.platform
property returns a string identifying the operating\nsystem platform on which the Node.js process is running. For instance\n'darwin'
, 'freebsd'
, 'linux'
, 'sunos'
or 'win32'
console.log(`This platform is ${process.platform}`);\n
\n"
},
{
"textRaw": "process.release",
"name": "release",
"meta": {
"added": [
"v3.0.0"
]
},
"desc": "The process.release
property returns an Object containing metadata related to\nthe current release, including URLs for the source tarball and headers-only\ntarball.
process.release
contains the following properties:
name
{String} A value that will always be 'node'
for Node.js. For\nlegacy io.js releases, this will be 'io.js'
.sourceUrl
{String} an absolute URL pointing to a .tar.gz
file containing\nthe source code of the current release.headersUrl
{String} an absolute URL pointing to a .tar.gz
file containing\nonly the source header files for the current release. This file is\nsignificantly smaller than the full source file and can be used for compiling\nNode.js native add-ons.libUrl
{String} an absolute URL pointing to a node.lib
file matching the\narchitecture and version of the current release. This file is used for\ncompiling Node.js native add-ons. This property is only present on Windows\nbuilds of Node.js and will be missing on all other platforms.lts
{String} a string label identifying the LTS label for this release.\nIf the Node.js release is not an LTS release, this will be undefined
.For example:
\n{\n name: 'node',\n lts: 'Argon',\n sourceUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5.tar.gz',\n headersUrl: 'https://nodejs.org/download/release/v4.4.5/node-v4.4.5-headers.tar.gz',\n libUrl: 'https://nodejs.org/download/release/v4.4.5/win-x64/node.lib'\n}\n
\nIn 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.
The process.stderr
property returns a Writable stream equivalent to or\nassociated with stderr
(fd 2
).
Note: process.stderr
and process.stdout
differ from other Node.js streams\nin several ways:
end()
will throw).'finish'
event.To check if Node.js is being run in a TTY context, read the isTTY
property\non process.stderr
, process.stdout
, or process.stdin
:
The process.stdin
property returns a Readable stream equivalent to or\nassociated with stdin
(fd 0
).
For example:
\nprocess.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
\nAs a Readable stream, process.stdin
can also be used in "old" mode that\nis compatible with scripts written for Node.js prior to v0.10.\nFor more information see Stream compatibility.
Note: In "old" streams mode the stdin
stream is paused by default, so one\nmust call process.stdin.resume()
to read from it. Note also that calling\nprocess.stdin.resume()
itself would switch stream to "old" mode.
The process.stdout
property returns a Writable stream equivalent to or\nassociated with stdout
(fd 1
).
For example:
\nconsole.log = (msg) => {\n process.stdout.write(`${msg}\\n`);\n};\n
\nNote: process.stderr
and process.stdout
differ from other Node.js streams\nin several ways:
end()
will throw).'finish'
event.To check if Node.js is being run in a TTY context, read the isTTY
property\non process.stderr
, process.stdout
, or process.stdin
:
The process.stderr
and process.stdout
streams are blocking when outputting\nto TTYs (terminals) on OS X as a workaround for the operating system's small,\n1kb buffer size. This is to prevent interleaving between stdout
and stderr
.
To check if Node.js is being run in a TTY context, check the isTTY
\nproperty on process.stderr
, process.stdout
, or process.stdin
.
For instance:
\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
\nSee the TTY documentation for more information.
\n" } ] }, { "textRaw": "`title` {String} ", "type": "String", "name": "title", "meta": { "added": [ "v0.1.104" ] }, "desc": "The process.title
property returns the current process title (i.e. returns\nthe current value of ps
). Assigning a new value to process.title
modifies\nthe current value of ps
.
Note: When a new value is assigned, different platforms will impose different\nmaximum length restrictions on the title. Usually such restrictions are quite\nlimited. For instance, on Linux and OS X, process.title
is limited to the size\nof the binary name plus the length of the command line arguments because setting\nthe process.title
overwrites the argv
memory of the process. Node.js v0.8\nallowed for longer process title strings by also overwriting the environ
\nmemory but that was potentially insecure and confusing in some (rather obscure)\ncases.
The process.version
property returns the Node.js version string.
console.log(`Version: ${process.version}`);\n
\n"
},
{
"textRaw": "`versions` {Object} ",
"type": "Object",
"name": "versions",
"meta": {
"added": [
"v0.2.0"
]
},
"desc": "The process.versions
property returns an object listing the version strings of\nNode.js and its dependencies. process.versions.modules
indicates the current\nABI version, which is increased whenever a C++ API changes. Node.js will refuse\nto load modules that were compiled against a different module ABI version.
console.log(process.versions);\n
\nWill generate output similar to:
\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 unicode: '8.0',\n cldr: '29.0',\n tz: '2016b' }\n
\n"
}
]
}
],
"vars": [
{
"textRaw": "\\_\\_dirname",
"name": "\\_\\_dirname",
"meta": {
"added": [
"v0.1.27"
]
},
"type": "var",
"desc": "The directory name of the current module. This the same as the\npath.dirname()
of the __filename
.
__dirname
is not actually a global but rather local to each module.
Example: running node example.js
from /Users/mjr
console.log(__dirname);\n// Prints: /Users/mjr\nconsole.log(path.dirname(__filename));\n// Prints: /Users/mjr\n
\n"
},
{
"textRaw": "\\_\\_filename",
"name": "\\_\\_filename",
"meta": {
"added": [
"v0.0.1"
]
},
"type": "var",
"desc": "The file name of the current module. This is the resolved absolute path of the\ncurrent module file.
\nFor a main program this is not necessarily the same as the file name used in the\ncommand line.
\nSee __dirname
for the directory name of the current module.
__filename
is not actually a global but rather local to each module.
Examples:
\nRunning node example.js
from /Users/mjr
console.log(__filename);\n// Prints: /Users/mjr/example.js\nconsole.log(__dirname);\n// Prints: /Users/mjr\n
\nGiven two modules: a
and b
, where b
is a dependency of\na
and there is a directory structure of:
/Users/mjr/app/a.js
/Users/mjr/app/node_modules/b/b.js
References to __filename
within b.js
will return\n/Users/mjr/app/node_modules/b/b.js
while references to __filename
within\na.js
will return /Users/mjr/app/a.js
.
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
.
exports
is not actually a global but rather local to each module.
See the module system documentation for more information.
\n" }, { "textRaw": "module", "name": "module", "meta": { "added": [ "v0.1.16" ] }, "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()
.
module
is not actually a global but rather local to each module.
See the module system documentation for more information.
\n" }, { "textRaw": "require()", "type": "var", "name": "require", "meta": { "added": [ "v0.1.13" ] }, "desc": "To require modules. See the Modules section. require
is not actually a\nglobal but rather local to each module.
Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require
will reload the module. Note that\nthis does not apply to native addons, for which reloading will result in an\nError.
Instruct require
on how to handle certain file extensions.
Process files with the extension .sjs
as .js
:
require.extensions['.sjs'] = require.extensions['.js'];\n
\nDeprecated In the past, this list has been used to load\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.
\nSince 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.
\nNote that the number of file system operations that the module system\nhas to perform in order to resolve a require(...)
statement to a\nfilename scales linearly with the number of registered extensions.
In other words, adding extensions slows down the module loader and\nshould be discouraged.
\n" } ], "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "meta": { "added": [ "v0.3.0" ] }, "desc": "Use the internal require()
machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.