{ "source": "doc/api/all.markdown", "miscs": [ { "textRaw": "About this Documentation", "name": "About this Documentation", "type": "misc", "desc": "

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

\n

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

\n

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

\n

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

\n", "miscs": [ { "textRaw": "Stability Index", "name": "Stability Index", "type": "misc", "desc": "

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

\n

The stability indices are as follows:\n\n

\n
Stability: 0 - Deprecated\nThis feature is known to be problematic, and changes are\nplanned.  Do not rely on it.  Use of the feature may cause warnings.  Backwards\ncompatibility should not be expected.
\n
Stability: 1 - Experimental\nThis feature was introduced recently, and may change\nor be removed in future versions.  Please try it out and provide feedback.\nIf it addresses a use-case that is important to you, tell the node core team.
\n
Stability: 2 - Unstable\nThe API is in the process of settling, but has not yet had\nsufficient real-world testing to be considered stable. Backwards-compatibility\nwill be maintained if reasonable.
\n
Stability: 3 - Stable\nThe API has proven satisfactory, but cleanup in the underlying\ncode may cause minor changes.  Backwards-compatibility is guaranteed.
\n
Stability: 4 - API Frozen\nThis API has been tested extensively in production and is\nunlikely to ever have to change.
\n
Stability: 5 - Locked\nUnless serious bugs are found, this code will not ever\nchange.  Please do not suggest changes in this area; they will be refused.
\n" }, { "textRaw": "JSON Output", "name": "json_output", "stability": 1, "stabilityText": "Experimental", "desc": "

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

\n

This feature is new as of node v0.6.12. It is experimental.\n\n

\n", "type": "misc", "displayName": "JSON Output" } ] }, { "textRaw": "Synopsis", "name": "Synopsis", "type": "misc", "desc": "

An example of a web server written with Node which responds with 'Hello\nWorld':\n\n

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

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

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

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

\n" }, { "textRaw": "Global Objects", "name": "Global Objects", "type": "misc", "desc": "

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

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

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

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

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

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

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

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

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

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

Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

\n

The timer functions are global variables. See the [timers][] section.\n\n

\n" }, { "textRaw": "console", "name": "console", "stability": 4, "stabilityText": "API Frozen", "type": "global", "desc": "

For printing to stdout and stderr. Similar to the console object functions\nprovided by most web browsers, here the output is sent to stdout or stderr.\n\n

\n

The console functions are synchronous when the destination is a terminal or\na file (to avoid lost messages in case of premature exit) and asynchronous\nwhen it's a pipe (to avoid blocking for long periods of time).\n\n

\n

That is, in the following example, stdout is non-blocking while stderr\nis blocking:\n\n

\n
$ node script.js 2> error.log | tee info.log
\n

In daily use, the blocking/non-blocking dichotomy is not something you\nshould worry about unless you log huge amounts of data.\n\n\n

\n", "methods": [ { "textRaw": "console.log([data], [...])", "type": "method", "name": "log", "desc": "

Prints to stdout with newline. This function can take multiple arguments in a\nprintf()-like way. Example:\n\n

\n
console.log('count: %d', count);
\n

If formatting elements are not found in the first string then util.inspect\nis used on each argument. See [util.format()][] for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.info([data], [...])", "type": "method", "name": "info", "desc": "

Same as console.log.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.error([data], [...])", "type": "method", "name": "error", "desc": "

Same as console.log but prints to stderr.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.warn([data], [...])", "type": "method", "name": "warn", "desc": "

Same as console.error.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.dir(obj)", "type": "method", "name": "dir", "desc": "

Uses util.inspect on obj and prints resulting string to stdout.\n\n

\n", "signatures": [ { "params": [ { "name": "obj" } ] } ] }, { "textRaw": "console.time(label)", "type": "method", "name": "time", "desc": "

Mark a time.\n\n

\n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "desc": "

Finish timer, record output. Example:\n\n

\n
console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');
\n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.trace(message, [...])", "type": "method", "name": "trace", "desc": "

Print to stderr 'Trace :', followed by the formatted message and stack trace\nto the current position.\n\n

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

Similar to [assert.ok()][], but the error message is formatted as\nutil.format(message...).\n\n

\n", "signatures": [ { "params": [ { "name": "value" }, { "name": "message", "optional": true }, { "name": "...", "optional": true } ] } ] } ] }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

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

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

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

\n

Example of listening for exit:\n\n

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

Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n

\n

Example of listening for uncaughtException:\n\n

\n
process.on('uncaughtException', function(err) {\n  console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function() {\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

Note that uncaughtException is a very crude mechanism for exception\nhandling and may be removed in the future.\n\n

\n

Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n

\n

Do not use it as the node.js equivalent of On Error Resume Next. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n

\n

Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n

\n

You have been warned.\n\n

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

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

\n

Example of listening for SIGINT:\n\n

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

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

\n

Note:\n\n

\n\n

Note that Windows does not support sending Signals, but node offers some\nemulation with process.kill(), and child_process.kill():\n- Sending signal 0 can be used to search for the existence of a process\n- Sending SIGINT, SIGTERM, and SIGKILL cause the unconditional exit of the\n target process.\n\n

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

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

\n

Example: the definition of console.log\n\n

\n
console.log = function(d) {\n  process.stdout.write(d + '\\n');\n};
\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking.\n\n

\n\n

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

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

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

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

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

\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking.\n\n

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

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

\n

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

\n
process.stdin.setEncoding('utf8');\n\nprocess.stdin.on('readable', function() {\n  var chunk = process.stdin.read();\n  if (chunk !== null) {\n    process.stdout.write('data: ' + chunk);\n  }\n});\n\nprocess.stdin.on('end', function() {\n  process.stdout.write('end');\n});
\n

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

\n

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

\n

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

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

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

\n
// print process.argv\nprocess.argv.forEach(function(val, index, array) {\n  console.log(index + ': ' + val);\n});
\n

This will generate:\n\n

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

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

\n

Example:\n\n

\n
/usr/local/bin/node
\n" }, { "textRaw": "process.execArgv", "name": "execArgv", "desc": "

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

\n

Example:\n\n

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

results in process.execArgv:\n\n

\n
['--harmony']
\n

and process.argv:\n\n

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

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

\n

An example of this object looks like:\n\n

\n
{ TERM: 'xterm-256color',\n  SHELL: '/usr/local/bin/bash',\n  USER: 'maciej',\n  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',\n  PWD: '/Users/maciej',\n  EDITOR: 'vim',\n  SHLVL: '1',\n  HOME: '/Users/maciej',\n  LOGNAME: 'maciej',\n  _: '/usr/local/bin/node' }
\n

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

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

But this will:\n\n

\n
process.env.foo = 'bar';\nconsole.log(process.env.foo);
\n" }, { "textRaw": "process.version", "name": "version", "desc": "

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

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

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

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

Will print something like:\n\n

\n
{ http_parser: '1.0',\n  node: '0.10.4',\n  v8: '3.14.5.8',\n  ares: '1.9.0-DEV',\n  uv: '0.10.3',\n  zlib: '1.2.3',\n  modules: '11',\n  openssl: '1.0.1e' }
\n" }, { "textRaw": "process.config", "name": "config", "desc": "

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

\n

An example of the possible output looks like:\n\n

\n
{ target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\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_v8: '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" }, { "textRaw": "process.pid", "name": "pid", "desc": "

The PID of the process.\n\n

\n
console.log('This process is pid ' + process.pid);
\n" }, { "textRaw": "process.title", "name": "title", "desc": "

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

\n

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

\n

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

\n

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

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

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

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

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

\n
console.log('This platform is ' + process.platform);
\n" }, { "textRaw": "`maxTickDepth` {Number} Default = 1000 ", "name": "maxTickDepth", "desc": "

Callbacks passed to process.nextTick will usually be called at the\nend of the current flow of execution, and are thus approximately as fast\nas calling a function synchronously. Left unchecked, this would starve\nthe event loop, preventing any I/O from occurring.\n\n

\n

Consider this code:\n\n

\n
process.nextTick(function foo() {\n  process.nextTick(foo);\n});
\n

In order to avoid the situation where Node is blocked by an infinite\nloop of recursive series of nextTick calls, it defers to allow some I/O\nto be done every so often.\n\n

\n

The process.maxTickDepth value is the maximum depth of\nnextTick-calling nextTick-callbacks that will be evaluated before\nallowing other forms of I/O to occur.\n\n

\n", "shortDesc": "Default = 1000" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "desc": "

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

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

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

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

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

\n
console.log('Current directory: ' + process.cwd());
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "desc": "

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

\n

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

\n
process.exit(1);
\n

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

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

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

\n

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

\n
if (process.getgid) {\n  console.log('Current gid: ' + process.getgid());\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "desc": "

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

\n

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

\n
if (process.getgid && process.setgid) {\n  console.log('Current gid: ' + process.getgid());\n  try {\n    process.setgid(501);\n    console.log('New gid: ' + process.getgid());\n  }\n  catch (err) {\n    console.log('Failed to set gid: ' + err);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "desc": "

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

\n

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

\n
if (process.getuid) {\n  console.log('Current uid: ' + process.getuid());\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "desc": "

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

\n

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

\n
if (process.getuid && process.setuid) {\n  console.log('Current uid: ' + process.getuid());\n  try {\n    process.setuid(501);\n    console.log('New uid: ' + process.getuid());\n  }\n  catch (err) {\n    console.log('Failed to set uid: ' + err);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "desc": "

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

\n

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

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

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

\n

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

\n

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

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

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

\n

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

\n

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

\n

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

\n
console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('bnoordhuis', 1000);   // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
\n", "signatures": [ { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ] }, { "textRaw": "process.kill(pid, [signal])", "type": "method", "name": "kill", "desc": "

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

\n

Will throw an error if target does not exist, and as a special case, a signal of\n0 can be used to test for the existence of a process.\n\n

\n

Note that just because the name of this function is process.kill, it is\nreally just a signal sender, like the kill system call. The signal sent\nmay do something other than kill the target process.\n\n

\n

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

\n
process.on('SIGHUP', function() {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function() {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
\n

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

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

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

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

This will generate:\n\n

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

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

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

On the next loop around the event loop call this callback.\nThis is not a simple alias to setTimeout(fn, 0), it's much more\nefficient. It typically runs before any other I/O events fire, but there\nare some exceptions. See process.maxTickDepth below.\n\n

\n
process.nextTick(function() {\n  console.log('nextTick callback');\n});
\n

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

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

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

\n
// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}
\n

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

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

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

\n

This approach is much better:\n\n

\n
function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}
\n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "desc": "

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

\n
var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n            ' to ' + newmask.toString(8));
\n", "signatures": [ { "params": [ { "name": "mask", "optional": true } ] } ] }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "desc": "

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

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

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

\n

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

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

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

\n", "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "desc": "

Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`cache` {Object} ", "name": "cache", "desc": "

Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

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

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

\n

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

\n
require.extensions['.sjs'] = require.extensions['.js'];
\n

Deprecated In the past, this list has been used to load\nnon-JavaScript modules into Node by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node program, or compiling them to\nJavaScript ahead of time.\n\n

\n

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

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

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

\n

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

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

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

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

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

\n

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

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

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

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

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

\n

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

\n

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

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

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

\n

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

\n

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

\n

See the [module section][] for more information.\n\n

\n" } ], "methods": [ { "textRaw": "setTimeout(cb, ms)", "type": "method", "name": "setTimeout", "desc": "

Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

\n

The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] }, { "textRaw": "clearTimeout(t)", "type": "method", "name": "clearTimeout", "desc": "

Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

\n", "signatures": [ { "params": [ { "name": "t" } ] } ] }, { "textRaw": "setInterval(cb, ms)", "type": "method", "name": "setInterval", "desc": "

Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

\n

The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] } ] }, { "textRaw": "Debugger", "name": "Debugger", "stability": 3, "stabilityText": "Stable", "type": "misc", "desc": "

V8 comes with an extensive debugger which is accessible out-of-process via a\nsimple TCP protocol.\nNode has a built-in client for this debugger. To use this, start Node with the\ndebug argument; a prompt will appear:\n\n

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

Node's debugger client doesn't support the full range of commands, but\nsimple step and inspection is possible. By putting the statement debugger;\ninto the source code of your script, you will enable a breakpoint.\n\n

\n

For example, suppose myscript.js looked like this:\n\n

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

Then once the debugger is run, it will break on line 4.\n\n

\n
% node debug myscript.js\n< debugger listening on port 5858\nconnecting... ok\nbreak in /home/indutny/Code/git/indutny/myscript.js:1\n  1 x = 5;\n  2 setTimeout(function () {\n  3   debugger;\ndebug> cont\n< hello\nbreak in /home/indutny/Code/git/indutny/myscript.js:3\n  1 x = 5;\n  2 setTimeout(function () {\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(function () {\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%
\n

The repl command allows you to evaluate code remotely. The next command\nsteps over to the next line. There are a few other commands available and more\nto come. Type help to see others.\n\n

\n", "miscs": [ { "textRaw": "Watchers", "name": "watchers", "desc": "

You can watch expression and variable values while debugging your code.\nOn every breakpoint each expression from the watchers list will be evaluated\nin the current context and displayed just before the breakpoint's source code\nlisting.\n\n

\n

To start watching an expression, type watch("my_expression"). watchers\nprints the active watchers. To remove a watcher, type\nunwatch("my_expression").\n\n

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

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

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

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

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

The V8 debugger can be enabled and accessed either by starting Node with\nthe --debug command-line flag or by signaling an existing Node process\nwith SIGUSR1.\n\n

\n

Once a process has been set in debug mode with this it can be connected to\nwith the node debugger. Either connect to the pid or the URI to the debugger.\nThe syntax is:\n\n

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

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

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

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

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

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

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

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

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

Stop a timer that was previously created with setInterval(). The callback\nwill not execute.\n\n

\n

The timer functions are global variables. See the [timers][] section.\n\n

\n" }, { "textRaw": "console", "name": "console", "stability": 4, "stabilityText": "API Frozen", "type": "global", "desc": "

For printing to stdout and stderr. Similar to the console object functions\nprovided by most web browsers, here the output is sent to stdout or stderr.\n\n

\n

The console functions are synchronous when the destination is a terminal or\na file (to avoid lost messages in case of premature exit) and asynchronous\nwhen it's a pipe (to avoid blocking for long periods of time).\n\n

\n

That is, in the following example, stdout is non-blocking while stderr\nis blocking:\n\n

\n
$ node script.js 2> error.log | tee info.log
\n

In daily use, the blocking/non-blocking dichotomy is not something you\nshould worry about unless you log huge amounts of data.\n\n\n

\n", "methods": [ { "textRaw": "console.log([data], [...])", "type": "method", "name": "log", "desc": "

Prints to stdout with newline. This function can take multiple arguments in a\nprintf()-like way. Example:\n\n

\n
console.log('count: %d', count);
\n

If formatting elements are not found in the first string then util.inspect\nis used on each argument. See [util.format()][] for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.info([data], [...])", "type": "method", "name": "info", "desc": "

Same as console.log.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.error([data], [...])", "type": "method", "name": "error", "desc": "

Same as console.log but prints to stderr.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.warn([data], [...])", "type": "method", "name": "warn", "desc": "

Same as console.error.\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "console.dir(obj)", "type": "method", "name": "dir", "desc": "

Uses util.inspect on obj and prints resulting string to stdout.\n\n

\n", "signatures": [ { "params": [ { "name": "obj" } ] } ] }, { "textRaw": "console.time(label)", "type": "method", "name": "time", "desc": "

Mark a time.\n\n

\n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "desc": "

Finish timer, record output. Example:\n\n

\n
console.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n  ;\n}\nconsole.timeEnd('100-elements');
\n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.trace(message, [...])", "type": "method", "name": "trace", "desc": "

Print to stderr 'Trace :', followed by the formatted message and stack trace\nto the current position.\n\n

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

Similar to [assert.ok()][], but the error message is formatted as\nutil.format(message...).\n\n

\n", "signatures": [ { "params": [ { "name": "value" }, { "name": "message", "optional": true }, { "name": "...", "optional": true } ] } ] } ] }, { "textRaw": "process", "name": "process", "type": "global", "desc": "

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

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

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

\n

Example of listening for exit:\n\n

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

Emitted when an exception bubbles all the way back to the event loop. If a\nlistener is added for this exception, the default action (which is to print\na stack trace and exit) will not occur.\n\n

\n

Example of listening for uncaughtException:\n\n

\n
process.on('uncaughtException', function(err) {\n  console.log('Caught exception: ' + err);\n});\n\nsetTimeout(function() {\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

Note that uncaughtException is a very crude mechanism for exception\nhandling and may be removed in the future.\n\n

\n

Don't use it, use domains instead. If you do use it, restart\nyour application after every unhandled exception!\n\n

\n

Do not use it as the node.js equivalent of On Error Resume Next. An\nunhandled exception means your application - and by extension node.js itself -\nis in an undefined state. Blindly resuming means anything could happen.\n\n

\n

Think of resuming as pulling the power cord when you are upgrading your system.\nNine out of ten times nothing happens - but the 10th time, your system is bust.\n\n

\n

You have been warned.\n\n

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

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

\n

Example of listening for SIGINT:\n\n

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

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

\n

Note:\n\n

\n\n

Note that Windows does not support sending Signals, but node offers some\nemulation with process.kill(), and child_process.kill():\n- Sending signal 0 can be used to search for the existence of a process\n- Sending SIGINT, SIGTERM, and SIGKILL cause the unconditional exit of the\n target process.\n\n

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

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

\n

Example: the definition of console.log\n\n

\n
console.log = function(d) {\n  process.stdout.write(d + '\\n');\n};
\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking.\n\n

\n\n

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

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

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

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

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

\n

process.stderr and process.stdout are unlike other streams in Node in\nthat writes to them are usually blocking.\n\n

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

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

\n

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

\n
process.stdin.setEncoding('utf8');\n\nprocess.stdin.on('readable', function() {\n  var chunk = process.stdin.read();\n  if (chunk !== null) {\n    process.stdout.write('data: ' + chunk);\n  }\n});\n\nprocess.stdin.on('end', function() {\n  process.stdout.write('end');\n});
\n

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

\n

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

\n

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

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

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

\n
// print process.argv\nprocess.argv.forEach(function(val, index, array) {\n  console.log(index + ': ' + val);\n});
\n

This will generate:\n\n

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

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

\n

Example:\n\n

\n
/usr/local/bin/node
\n" }, { "textRaw": "process.execArgv", "name": "execArgv", "desc": "

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

\n

Example:\n\n

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

results in process.execArgv:\n\n

\n
['--harmony']
\n

and process.argv:\n\n

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

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

\n

An example of this object looks like:\n\n

\n
{ TERM: 'xterm-256color',\n  SHELL: '/usr/local/bin/bash',\n  USER: 'maciej',\n  PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',\n  PWD: '/Users/maciej',\n  EDITOR: 'vim',\n  SHLVL: '1',\n  HOME: '/Users/maciej',\n  LOGNAME: 'maciej',\n  _: '/usr/local/bin/node' }
\n

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

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

But this will:\n\n

\n
process.env.foo = 'bar';\nconsole.log(process.env.foo);
\n" }, { "textRaw": "process.version", "name": "version", "desc": "

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

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

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

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

Will print something like:\n\n

\n
{ http_parser: '1.0',\n  node: '0.10.4',\n  v8: '3.14.5.8',\n  ares: '1.9.0-DEV',\n  uv: '0.10.3',\n  zlib: '1.2.3',\n  modules: '11',\n  openssl: '1.0.1e' }
\n" }, { "textRaw": "process.config", "name": "config", "desc": "

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

\n

An example of the possible output looks like:\n\n

\n
{ target_defaults:\n   { cflags: [],\n     default_configuration: 'Release',\n     defines: [],\n     include_dirs: [],\n     libraries: [] },\n  variables:\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_v8: '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" }, { "textRaw": "process.pid", "name": "pid", "desc": "

The PID of the process.\n\n

\n
console.log('This process is pid ' + process.pid);
\n" }, { "textRaw": "process.title", "name": "title", "desc": "

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

\n

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

\n

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

\n

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

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

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

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

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

\n
console.log('This platform is ' + process.platform);
\n" }, { "textRaw": "`maxTickDepth` {Number} Default = 1000 ", "name": "maxTickDepth", "desc": "

Callbacks passed to process.nextTick will usually be called at the\nend of the current flow of execution, and are thus approximately as fast\nas calling a function synchronously. Left unchecked, this would starve\nthe event loop, preventing any I/O from occurring.\n\n

\n

Consider this code:\n\n

\n
process.nextTick(function foo() {\n  process.nextTick(foo);\n});
\n

In order to avoid the situation where Node is blocked by an infinite\nloop of recursive series of nextTick calls, it defers to allow some I/O\nto be done every so often.\n\n

\n

The process.maxTickDepth value is the maximum depth of\nnextTick-calling nextTick-callbacks that will be evaluated before\nallowing other forms of I/O to occur.\n\n

\n", "shortDesc": "Default = 1000" } ], "methods": [ { "textRaw": "process.abort()", "type": "method", "name": "abort", "desc": "

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

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

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

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

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

\n
console.log('Current directory: ' + process.cwd());
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.exit([code])", "type": "method", "name": "exit", "desc": "

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

\n

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

\n
process.exit(1);
\n

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

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

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

\n

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

\n
if (process.getgid) {\n  console.log('Current gid: ' + process.getgid());\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setgid(id)", "type": "method", "name": "setgid", "desc": "

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

\n

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

\n
if (process.getgid && process.setgid) {\n  console.log('Current gid: ' + process.getgid());\n  try {\n    process.setgid(501);\n    console.log('New gid: ' + process.getgid());\n  }\n  catch (err) {\n    console.log('Failed to set gid: ' + err);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getuid()", "type": "method", "name": "getuid", "desc": "

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

\n

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

\n
if (process.getuid) {\n  console.log('Current uid: ' + process.getuid());\n}
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "process.setuid(id)", "type": "method", "name": "setuid", "desc": "

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

\n

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

\n
if (process.getuid && process.setuid) {\n  console.log('Current uid: ' + process.getuid());\n  try {\n    process.setuid(501);\n    console.log('New uid: ' + process.getuid());\n  }\n  catch (err) {\n    console.log('Failed to set uid: ' + err);\n  }\n}
\n", "signatures": [ { "params": [ { "name": "id" } ] } ] }, { "textRaw": "process.getgroups()", "type": "method", "name": "getgroups", "desc": "

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

\n

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

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

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

\n

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

\n

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

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

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

\n

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

\n

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

\n

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

\n
console.log(process.getgroups());         // [ 0 ]\nprocess.initgroups('bnoordhuis', 1000);   // switch user\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000, 0 ]\nprocess.setgid(1000);                     // drop root gid\nconsole.log(process.getgroups());         // [ 27, 30, 46, 1000 ]
\n", "signatures": [ { "params": [ { "name": "user" }, { "name": "extra_group" } ] } ] }, { "textRaw": "process.kill(pid, [signal])", "type": "method", "name": "kill", "desc": "

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

\n

Will throw an error if target does not exist, and as a special case, a signal of\n0 can be used to test for the existence of a process.\n\n

\n

Note that just because the name of this function is process.kill, it is\nreally just a signal sender, like the kill system call. The signal sent\nmay do something other than kill the target process.\n\n

\n

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

\n
process.on('SIGHUP', function() {\n  console.log('Got SIGHUP signal.');\n});\n\nsetTimeout(function() {\n  console.log('Exiting.');\n  process.exit(0);\n}, 100);\n\nprocess.kill(process.pid, 'SIGHUP');
\n

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

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

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

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

This will generate:\n\n

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

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

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

On the next loop around the event loop call this callback.\nThis is not a simple alias to setTimeout(fn, 0), it's much more\nefficient. It typically runs before any other I/O events fire, but there\nare some exceptions. See process.maxTickDepth below.\n\n

\n
process.nextTick(function() {\n  console.log('nextTick callback');\n});
\n

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

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

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

\n
// WARNING!  DO NOT USE!  BAD UNSAFE HAZARD!\nfunction maybeSync(arg, cb) {\n  if (arg) {\n    cb();\n    return;\n  }\n\n  fs.stat('file', cb);\n}
\n

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

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

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

\n

This approach is much better:\n\n

\n
function definitelyAsync(arg, cb) {\n  if (arg) {\n    process.nextTick(cb);\n    return;\n  }\n\n  fs.stat('file', cb);\n}
\n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "process.umask([mask])", "type": "method", "name": "umask", "desc": "

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

\n
var oldmask, newmask = 0644;\n\noldmask = process.umask(newmask);\nconsole.log('Changed umask from: ' + oldmask.toString(8) +\n            ' to ' + newmask.toString(8));
\n", "signatures": [ { "params": [ { "name": "mask", "optional": true } ] } ] }, { "textRaw": "process.uptime()", "type": "method", "name": "uptime", "desc": "

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

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

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

\n

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

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

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

\n", "methods": [ { "textRaw": "require.resolve()", "type": "method", "name": "resolve", "desc": "

Use the internal require() machinery to look up the location of a module,\nbut rather than loading the module, just return the resolved filename.\n\n

\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "`cache` {Object} ", "name": "cache", "desc": "

Modules are cached in this object when they are required. By deleting a key\nvalue from this object, the next require will reload the module.\n\n

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

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

\n

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

\n
require.extensions['.sjs'] = require.extensions['.js'];
\n

Deprecated In the past, this list has been used to load\nnon-JavaScript modules into Node by compiling them on-demand.\nHowever, in practice, there are much better ways to do this, such as\nloading modules via some other Node program, or compiling them to\nJavaScript ahead of time.\n\n

\n

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

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

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

\n

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

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

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

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

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

\n

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

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

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

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

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

\n

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

\n

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

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

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

\n

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

\n

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

\n

See the [module section][] for more information.\n\n

\n" } ], "methods": [ { "textRaw": "setTimeout(cb, ms)", "type": "method", "name": "setTimeout", "desc": "

Run callback cb after at least ms milliseconds. The actual delay depends\non external factors like OS timer granularity and system load.\n\n

\n

The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] }, { "textRaw": "clearTimeout(t)", "type": "method", "name": "clearTimeout", "desc": "

Stop a timer that was previously created with setTimeout(). The callback will\nnot execute.\n\n

\n", "signatures": [ { "params": [ { "name": "t" } ] } ] }, { "textRaw": "setInterval(cb, ms)", "type": "method", "name": "setInterval", "desc": "

Run callback cb repeatedly every ms milliseconds. Note that the actual\ninterval may vary, depending on external factors like OS timer granularity and\nsystem load. It's never less than ms but it may be longer.\n\n

\n

The interval must be in the range of 1-2,147,483,647 inclusive. If the value is\noutside that range, it's changed to 1 millisecond. Broadly speaking, a timer\ncannot span more than 24.8 days.\n\n

\n

Returns an opaque value that represents the timer.\n\n

\n", "signatures": [ { "params": [ { "name": "cb" }, { "name": "ms" } ] } ] } ], "modules": [ { "textRaw": "Timers", "name": "timers", "stability": 5, "stabilityText": "Locked", "desc": "

All of the timer functions are globals. You do not need to require()\nthis module in order to use them.\n\n

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

To schedule execution of a one-time callback after delay milliseconds. Returns a\ntimeoutObject for possible use with clearTimeout(). Optionally you can\nalso pass arguments to the callback.\n\n

\n

It is important to note that your callback will probably not be called in exactly\ndelay milliseconds - Node.js makes no guarantees about the exact timing of when\nthe callback will fire, nor of the ordering things will fire in. The callback will\nbe called as close as possible to the time specified.\n\n

\n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearTimeout(timeoutObject)", "type": "method", "name": "clearTimeout", "desc": "

Prevents a timeout from triggering.\n\n

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

To schedule the repeated execution of callback every delay milliseconds.\nReturns a intervalObject for possible use with clearInterval(). Optionally\nyou can also pass arguments to the callback.\n\n

\n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "delay" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearInterval(intervalObject)", "type": "method", "name": "clearInterval", "desc": "

Stops an interval from triggering.\n\n

\n", "signatures": [ { "params": [ { "name": "intervalObject" } ] } ] }, { "textRaw": "unref()", "type": "method", "name": "unref", "desc": "

The opaque value returned by setTimeout and setInterval also has the method\ntimer.unref() which will allow you to create a timer that is active but if\nit is the only item left in the event loop won't keep the program running.\nIf the timer is already unrefd calling unref again will have no effect.\n\n

\n

In the case of setTimeout when you unref you create a separate timer that\nwill wakeup the event loop, creating too many of these may adversely effect\nevent loop performance -- use wisely.\n\n

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

If you had previously unref()d a timer you can call ref() to explicitly\nrequest the timer hold the program open. If the timer is already refd calling\nref again will have no effect.\n\n

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

To schedule the "immediate" execution of callback after I/O events\ncallbacks and before setTimeout and setInterval . Returns an\nimmediateObject for possible use with clearImmediate(). Optionally you\ncan also pass arguments to the callback.\n\n

\n

Immediates are queued in the order created, and are popped off the queue once\nper loop iteration. This is different from process.nextTick which will\nexecute process.maxTickDepth queued callbacks per iteration. setImmediate\nwill yield to the event loop after firing a queued callback to make sure I/O is\nnot being starved. While order is preserved for execution, other I/O events may\nfire between any two scheduled immediate callbacks.\n\n

\n", "signatures": [ { "params": [ { "name": "callback" }, { "name": "arg", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "clearImmediate(immediateObject)", "type": "method", "name": "clearImmediate", "desc": "

Stops an immediate from triggering.\n\n

\n", "signatures": [ { "params": [ { "name": "immediateObject" } ] } ] } ], "type": "module", "displayName": "Timers" }, { "textRaw": "Modules", "name": "module", "stability": 5, "stabilityText": "Locked", "desc": "

Node has a simple module loading system. In Node, files and modules are in\none-to-one correspondence. As an example, foo.js loads the module\ncircle.js in the same directory.\n\n

\n

The contents of foo.js:\n\n

\n
var circle = require('./circle.js');\nconsole.log( 'The area of a circle of radius 4 is '\n           + circle.area(4));
\n

The contents of circle.js:\n\n

\n
var PI = Math.PI;\n\nexports.area = function (r) {\n  return PI * r * r;\n};\n\nexports.circumference = function (r) {\n  return 2 * PI * r;\n};
\n

The module circle.js has exported the functions area() and\ncircumference(). To add functions and objects to the root of your module,\nyou can add them to the special exports object.\n\n

\n

Variables local to the module will be private, as though the module was wrapped\nin a function. In this example the variable PI is private to circle.js.\n\n

\n

If you want the root of your module's export to be a function (such as a\nconstructor) or if you want to export a complete object in one assignment\ninstead of building it one property at a time, assign it to module.exports\ninstead of exports.\n\n

\n

Below, bar.js makes use of the square module, which exports a constructor:\n\n

\n
var square = require('./square.js');\nvar mySquare = square(2);\nconsole.log('The area of my square is ' + mySquare.area());
\n

The square module is defined in square.js:\n\n

\n
// assigning to exports will not modify module, must use module.exports\nmodule.exports = function(width) {\n  return {\n    area: function() {\n      return width * width;\n    }\n  };\n}
\n

The module system is implemented in the require("module") module.\n\n

\n", "miscs": [ { "textRaw": "Cycles", "name": "Cycles", "type": "misc", "desc": "

When there are circular require() calls, a module might not be\ndone being executed when it is returned.\n\n

\n

Consider this situation:\n\n

\n

a.js:\n\n

\n
console.log('a starting');\nexports.done = false;\nvar b = require('./b.js');\nconsole.log('in a, b.done = %j', b.done);\nexports.done = true;\nconsole.log('a done');
\n

b.js:\n\n

\n
console.log('b starting');\nexports.done = false;\nvar a = require('./a.js');\nconsole.log('in b, a.done = %j', a.done);\nexports.done = true;\nconsole.log('b done');
\n

main.js:\n\n

\n
console.log('main starting');\nvar a = require('./a.js');\nvar b = require('./b.js');\nconsole.log('in main, a.done=%j, b.done=%j', a.done, b.done);
\n

When main.js loads a.js, then a.js in turn loads b.js. At that\npoint, b.js tries to load a.js. In order to prevent an infinite\nloop an unfinished copy of the a.js exports object is returned to the\nb.js module. b.js then finishes loading, and its exports object is\nprovided to the a.js module.\n\n

\n

By the time main.js has loaded both modules, they're both finished.\nThe output of this program would thus be:\n\n

\n
$ node main.js\nmain starting\na starting\nb starting\nin b, a.done = false\nb done\nin a, b.done = true\na done\nin main, a.done=true, b.done=true
\n

If you have cyclic module dependencies in your program, make sure to\nplan accordingly.\n\n

\n" }, { "textRaw": "Core Modules", "name": "Core Modules", "type": "misc", "desc": "

Node has several modules compiled into the binary. These modules are\ndescribed in greater detail elsewhere in this documentation.\n\n

\n

The core modules are defined in node's source in the lib/ folder.\n\n

\n

Core modules are always preferentially loaded if their identifier is\npassed to require(). For instance, require('http') will always\nreturn the built in HTTP module, even if there is a file by that name.\n\n

\n" }, { "textRaw": "File Modules", "name": "File Modules", "type": "misc", "desc": "

If the exact filename is not found, then node will attempt to load the\nrequired filename with the added extension of .js, .json, and then .node.\n\n

\n

.js files are interpreted as JavaScript text files, and .json files are\nparsed as JSON text files. .node files are interpreted as compiled addon\nmodules loaded with dlopen.\n\n

\n

A module prefixed with '/' is an absolute path to the file. For\nexample, require('/home/marco/foo.js') will load the file at\n/home/marco/foo.js.\n\n

\n

A module prefixed with './' is relative to the file calling require().\nThat is, circle.js must be in the same directory as foo.js for\nrequire('./circle') to find it.\n\n

\n

Without a leading '/' or './' to indicate a file, the module is either a\n"core module" or is loaded from a node_modules folder.\n\n

\n

If the given path does not exist, require() will throw an Error with its\ncode property set to 'MODULE_NOT_FOUND'.\n\n

\n" }, { "textRaw": "Loading from `node_modules` Folders", "name": "Loading from `node_modules` Folders", "type": "misc", "desc": "

If the module identifier passed to require() is not a native module,\nand does not begin with '/', '../', or './', then node starts at the\nparent directory of the current module, and adds /node_modules, and\nattempts to load the module from that location.\n\n

\n

If it is not found there, then it moves to the parent directory, and so\non, until the root of the file system is reached.\n\n

\n

For example, if the file at '/home/ry/projects/foo.js' called\nrequire('bar.js'), then node would look in the following locations, in\nthis order:\n\n

\n\n

This allows programs to localize their dependencies, so that they do not\nclash.\n\n

\n" }, { "textRaw": "Folders as Modules", "name": "Folders as Modules", "type": "misc", "desc": "

It is convenient to organize programs and libraries into self-contained\ndirectories, and then provide a single entry point to that library.\nThere are three ways in which a folder may be passed to require() as\nan argument.\n\n

\n

The first is to create a package.json file in the root of the folder,\nwhich specifies a main module. An example package.json file might\nlook like this:\n\n

\n
{ "name" : "some-library",\n  "main" : "./lib/some-library.js" }
\n

If this was in a folder at ./some-library, then\nrequire('./some-library') would attempt to load\n./some-library/lib/some-library.js.\n\n

\n

This is the extent of Node's awareness of package.json files.\n\n

\n

If there is no package.json file present in the directory, then node\nwill attempt to load an index.js or index.node file out of that\ndirectory. For example, if there was no package.json file in the above\nexample, then require('./some-library') would attempt to load:\n\n

\n\n" }, { "textRaw": "Caching", "name": "Caching", "type": "misc", "desc": "

Modules are cached after the first time they are loaded. This means\n(among other things) that every call to require('foo') will get\nexactly the same object returned, if it would resolve to the same file.\n\n

\n

Multiple calls to require('foo') may not cause the module code to be\nexecuted multiple times. This is an important feature. With it,\n"partially done" objects can be returned, thus allowing transitive\ndependencies to be loaded even when they would cause cycles.\n\n

\n

If you want to have a module execute code multiple times, then export a\nfunction, and call that function.\n\n

\n", "miscs": [ { "textRaw": "Module Caching Caveats", "name": "Module Caching Caveats", "type": "misc", "desc": "

Modules are cached based on their resolved filename. Since modules may\nresolve to a different filename based on the location of the calling\nmodule (loading from node_modules folders), it is not a guarantee\nthat require('foo') will always return the exact same object, if it\nwould resolve to different files.\n\n

\n" } ] }, { "textRaw": "All Together...", "name": "All Together...", "type": "misc", "desc": "

To get the exact filename that will be loaded when require() is called, use\nthe require.resolve() function.\n\n

\n

Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:\n\n

\n
require(X) from module at path Y\n1. If X is a core module,\n   a. return the core module\n   b. STOP\n2. If X begins with './' or '/' or '../'\n   a. LOAD_AS_FILE(Y + X)\n   b. LOAD_AS_DIRECTORY(Y + X)\n3. LOAD_NODE_MODULES(X, dirname(Y))\n4. THROW "not found"\n\nLOAD_AS_FILE(X)\n1. If X is a file, load X as JavaScript text.  STOP\n2. If X.js is a file, load X.js as JavaScript text.  STOP\n3. If X.json is a file, parse X.json to a JavaScript Object.  STOP\n4. If X.node is a file, load X.node as binary addon.  STOP\n\nLOAD_AS_DIRECTORY(X)\n1. If X/package.json is a file,\n   a. Parse X/package.json, and look for "main" field.\n   b. let M = X + (json main field)\n   c. LOAD_AS_FILE(M)\n2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP\n3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP\n4. If X/index.node is a file, load X/index.node as binary addon.  STOP\n\nLOAD_NODE_MODULES(X, START)\n1. let DIRS=NODE_MODULES_PATHS(START)\n2. for each DIR in DIRS:\n   a. LOAD_AS_FILE(DIR/X)\n   b. LOAD_AS_DIRECTORY(DIR/X)\n\nNODE_MODULES_PATHS(START)\n1. let PARTS = path split(START)\n2. let I = count of PARTS - 1\n3. let DIRS = []\n4. while I >= 0,\n   a. if PARTS[I] = "node_modules" CONTINUE\n   c. DIR = path join(PARTS[0 .. I] + "node_modules")\n   b. DIRS = DIRS + DIR\n   c. let I = I - 1\n5. return DIRS
\n" }, { "textRaw": "Loading from the global folders", "name": "Loading from the global folders", "type": "misc", "desc": "

If the NODE_PATH environment variable is set to a colon-delimited list\nof absolute paths, then node will search those paths for modules if they\nare not found elsewhere. (Note: On Windows, NODE_PATH is delimited by\nsemicolons instead of colons.)\n\n

\n

Additionally, node will search in the following locations:\n\n

\n\n

Where $HOME is the user's home directory, and $PREFIX is node's\nconfigured node_prefix.\n\n

\n

These are mostly for historic reasons. You are highly encouraged to\nplace your dependencies locally in node_modules folders. They will be\nloaded faster, and more reliably.\n\n

\n" }, { "textRaw": "Accessing the main module", "name": "Accessing the main module", "type": "misc", "desc": "

When a file is run directly from Node, require.main is set to its\nmodule. That means that you can determine whether a file has been run\ndirectly by testing\n\n

\n
require.main === module
\n

For a file foo.js, this will be true if run via node foo.js, but\nfalse if run by require('./foo').\n\n

\n

Because module provides a filename property (normally equivalent to\n__filename), the entry point of the current application can be obtained\nby checking require.main.filename.\n\n

\n" }, { "textRaw": "Addenda: Package Manager Tips", "name": "Addenda: Package Manager Tips", "type": "misc", "desc": "

The semantics of Node's require() function were designed to be general\nenough to support a number of sane directory structures. Package manager\nprograms such as dpkg, rpm, and npm will hopefully find it possible to\nbuild native packages from Node modules without modification.\n\n

\n

Below we give a suggested directory structure that could work:\n\n

\n

Let's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version> hold the contents of a\nspecific version of a package.\n\n

\n

Packages can depend on one another. In order to install package foo, you\nmay have to install a specific version of package bar. The bar package\nmay itself have dependencies, and in some cases, these dependencies may even\ncollide or form cycles.\n\n

\n

Since Node looks up the realpath of any modules it loads (that is,\nresolves symlinks), and then looks for their dependencies in the\nnode_modules folders as described above, this situation is very simple to\nresolve with the following architecture:\n\n

\n\n

Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.\n\n

\n

When the code in the foo package does require('bar'), it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar.\nThen, when the code in the bar package calls require('quux'), it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux.\n\n

\n

Furthermore, to make the module lookup process even more optimal, rather\nthan putting packages directly in /usr/lib/node, we could put them in\n/usr/lib/node_modules/<name>/<version>. Then node will not bother\nlooking for missing dependencies in /usr/node_modules or /node_modules.\n\n

\n

In order to make modules available to the node REPL, it might be useful to\nalso add the /usr/lib/node_modules folder to the $NODE_PATH environment\nvariable. Since the module lookups using node_modules folders are all\nrelative, and based on the real path of the files making the calls to\nrequire(), the packages themselves can be anywhere.\n\n

\n" } ], "vars": [ { "textRaw": "The `module` Object", "name": "module", "type": "var", "desc": "

In each module, the module free variable is a reference to the object\nrepresenting the current module. For convenience, module.exports is\nalso accessible via the exports module-global. module isn't actually\na global but rather local to each module.\n\n

\n", "properties": [ { "textRaw": "`exports` {Object} ", "name": "exports", "desc": "

The module.exports object is created by the Module system. Sometimes this is not\nacceptable; many want their module to be an instance of some class. To do this\nassign the desired export object to module.exports. Note that assigning the\ndesired object to exports will simply rebind the local exports variable,\nwhich is probably not what you want to do.\n\n

\n

For example suppose we were making a module called a.js\n\n

\n
var EventEmitter = require('events').EventEmitter;\n\nmodule.exports = new EventEmitter();\n\n// Do some work, and after some time emit\n// the 'ready' event from the module itself.\nsetTimeout(function() {\n  module.exports.emit('ready');\n}, 1000);
\n

Then in another file we could do\n\n

\n
var a = require('./a');\na.on('ready', function() {\n  console.log('module a is ready');\n});
\n

Note that assignment to module.exports must be done immediately. It cannot be\ndone in any callbacks. This does not work:\n\n

\n

x.js:\n\n

\n
setTimeout(function() {\n  module.exports = { a: "hello" };\n}, 0);
\n

y.js:\n\n

\n
var x = require('./x');\nconsole.log(x.a);
\n", "modules": [ { "textRaw": "exports alias", "name": "exports_alias", "desc": "

The exports variable that is available within a module starts as a reference\nto module.exports. As with any variable, if you assign a new value to it, it\nis no longer bound to the previous value.\n\n

\n

To illustrate the behaviour, imagine this hypothetical implementation of\nrequire():\n\n

\n
function require(...) {\n  // ...\n  function (module, exports) {\n    // Your module code here\n    exports = some_func;        // re-assigns exports, exports is no longer\n                                // a shortcut, and nothing is exported.\n    module.exports = some_func; // makes your module export 0\n  } (module, module.exports);\n  return module;\n}
\n

As a guideline, if the relationship between exports and module.exports\nseems like magic to you, ignore exports and only use module.exports.\n\n

\n", "type": "module", "displayName": "exports alias" } ] }, { "textRaw": "`id` {String} ", "name": "id", "desc": "

The identifier for the module. Typically this is the fully resolved\nfilename.\n\n\n

\n" }, { "textRaw": "`filename` {String} ", "name": "filename", "desc": "

The fully resolved filename to the module.\n\n\n

\n" }, { "textRaw": "`loaded` {Boolean} ", "name": "loaded", "desc": "

Whether or not the module is done loading, or is in the process of\nloading.\n\n\n

\n" }, { "textRaw": "`parent` {Module Object} ", "name": "parent", "desc": "

The module that required this one.\n\n\n

\n" }, { "textRaw": "`children` {Array} ", "name": "children", "desc": "

The module objects required by this one.\n\n\n\n

\n" } ], "methods": [ { "textRaw": "module.require(id)", "type": "method", "name": "require", "signatures": [ { "return": { "textRaw": "Return: {Object} `module.exports` from the resolved module ", "name": "return", "type": "Object", "desc": "`module.exports` from the resolved module" }, "params": [ { "textRaw": "`id` {String} ", "name": "id", "type": "String" } ] }, { "params": [ { "name": "id" } ] } ], "desc": "

The module.require method provides a way to load a module as if\nrequire() was called from the original module.\n\n

\n

Note that in order to do this, you must get a reference to the module\nobject. Since require() returns the module.exports, and the module is\ntypically only available within a specific module's code, it must be\nexplicitly exported in order to be used.\n\n\n

\n" } ] } ], "type": "module", "displayName": "module" }, { "textRaw": "Addons", "name": "addons", "desc": "

Addons are dynamically linked shared objects. They can provide glue to C and\nC++ libraries. The API (at the moment) is rather complex, involving\nknowledge of several libraries:\n\n

\n\n

Node statically compiles all its dependencies into the executable.\nWhen compiling your module, you don't need to worry about linking to\nany of these libraries.\n\n

\n

All of the following examples are available for\ndownload and may be\nused as a starting-point for your own Addon.\n\n

\n", "modules": [ { "textRaw": "Hello world", "name": "hello_world", "desc": "

To get started let's make a small Addon which is the C++ equivalent of\nthe following JavaScript code:\n\n

\n
module.exports.hello = function() { return 'world'; };
\n

First we create a file hello.cc:\n\n

\n
#include <node.h>\n#include <v8.h>\n\nusing namespace v8;\n\nHandle<Value> Method(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("world"));\n}\n\nvoid init(Handle<Object> exports) {\n  exports->Set(String::NewSymbol("hello"),\n      FunctionTemplate::New(Method)->GetFunction());\n}\n\nNODE_MODULE(hello, init)
\n

Note that all Node addons must export an initialization function:\n\n

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

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

\n

The module_name needs to match the filename of the final binary (minus the\n.node suffix).\n\n

\n

The source code needs to be built into hello.node, the binary Addon. To\ndo this we create a file called binding.gyp which describes the configuration\nto build your module in a JSON-like format. This file gets compiled by\nnode-gyp.\n\n

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

The next step is to generate the appropriate project build files for the\ncurrent platform. Use node-gyp configure for that.\n\n

\n

Now you will have either a Makefile (on Unix platforms) or a vcxproj file\n(on Windows) in the build/ directory. Next invoke the node-gyp build\ncommand.\n\n

\n

Now you have your compiled .node bindings file! The compiled bindings end up\nin build/Release/.\n\n

\n

You can now use the binary addon in a Node project hello.js by pointing require to\nthe recently built hello.node module:\n\n

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

Please see patterns below for further information or\n

\n

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

\n", "type": "module", "displayName": "Hello world" }, { "textRaw": "Addon patterns", "name": "addon_patterns", "desc": "

Below are some addon patterns to help you get started. Consult the online\nv8 reference for help with the various v8\ncalls, and v8's Embedder's Guide\nfor an explanation of several concepts used such as handles, scopes,\nfunction templates, etc.\n\n

\n

In order to use these examples you need to compile them using node-gyp.\nCreate the following binding.gyp file:\n\n

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

In cases where there is more than one .cc file, simply add the file name to the\nsources array, e.g.:\n\n

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

Now that you have your binding.gyp ready, you can configure and build the\naddon:\n\n

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

The following pattern illustrates how to read arguments from JavaScript\nfunction calls and return a result. This is the main and only needed source\naddon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\n\n  if (args.Length() < 2) {\n    ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));\n    return scope.Close(Undefined());\n  }\n\n  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {\n    ThrowException(Exception::TypeError(String::New("Wrong arguments")));\n    return scope.Close(Undefined());\n  }\n\n  Local<Number> num = Number::New(args[0]->NumberValue() +\n      args[1]->NumberValue());\n  return scope.Close(num);\n}\n\nvoid Init(Handle<Object> exports) {\n  exports->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

You can test it with the following JavaScript snippet:\n\n

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

You can pass JavaScript functions to a C++ function and execute them from\nthere. Here's addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> RunCallback(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Function> cb = Local<Function>::Cast(args[0]);\n  const unsigned argc = 1;\n  Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };\n  cb->Call(Context::GetCurrent()->Global(), argc, argv);\n\n  return scope.Close(Undefined());\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(RunCallback)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

Note that this example uses a two-argument form of Init() that receives\nthe full module object as the second argument. This allows the addon\nto completely overwrite exports with a single function instead of\nadding the function as a property of exports.\n\n

\n

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

\n
var addon = require('./build/Release/addon');\n\naddon(function(msg){\n  console.log(msg); // 'hello world'\n});
\n", "type": "module", "displayName": "Callbacks" }, { "textRaw": "Object factory", "name": "object_factory", "desc": "

You can create and return new objects from within a C++ function with this\naddon.cc pattern, which returns an object with property msg that echoes\nthe string passed to createObject():\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n\n  Local<Object> obj = Object::New();\n  obj->Set(String::NewSymbol("msg"), args[0]->ToString());\n\n  return scope.Close(obj);\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

To test it in JavaScript:\n\n

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

This pattern illustrates how to create and return a JavaScript function that\nwraps a C++ function:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n\nusing namespace v8;\n\nHandle<Value> MyFunction(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(String::New("hello world"));\n}\n\nHandle<Value> CreateFunction(const Arguments& args) {\n  HandleScope scope;\n\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);\n  Local<Function> fn = tpl->GetFunction();\n  fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous\n\n  return scope.Close(fn);\n}\n\nvoid Init(Handle<Object> exports, Handle<Object> module) {\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateFunction)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\n

To test:\n\n

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

Here we will create a wrapper for a C++ object/class MyObject that can be\ninstantiated in JavaScript through the new operator. First prepare the main\nmodule addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nvoid InitAll(Handle<Object> exports) {\n  MyObject::Init(exports);\n}\n\nNODE_MODULE(addon, InitAll)
\n

Then in myobject.h make your wrapper inherit from node::ObjectWrap:\n\n

\n
#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init(v8::Handle<v8::Object> exports);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
\n

And in myobject.cc implement the various methods that you want to expose.\nHere we expose the method plusOne by adding it to the constructor's\nprototype:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init(Handle<Object> exports) {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n  exports->Set(String::NewSymbol("MyObject"), constructor);\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\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    return 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    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  return scope.Close(Number::New(obj->value_));\n}
\n

Test it with:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj = new addon.MyObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13
\n", "type": "module", "displayName": "Wrapping C++ objects" }, { "textRaw": "Factory of wrapped objects", "name": "factory_of_wrapped_objects", "desc": "

This is useful when you want to be able to create native objects without\nexplicitly instantiating them with the new operator in JavaScript, e.g.\n\n

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

Let's register our createObject method in addon.cc:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nvoid InitAll(Handle<Object> exports, Handle<Object> module) {\n  MyObject::Init();\n\n  module->Set(String::NewSymbol("exports"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
\n

In myobject.h we now introduce the static method NewInstance that takes\ncare of instantiating the object (i.e. it does the job of new in JavaScript):\n\n

\n
#define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
\n

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

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  // Prototype\n  tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),\n      FunctionTemplate::New(PlusOne)->GetFunction());\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\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    return 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    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n  HandleScope scope;\n\n  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n  obj->value_ += 1;\n\n  return scope.Close(Number::New(obj->value_));\n}
\n

Test it with:\n\n

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

In addition to wrapping and returning C++ objects, you can pass them around\nby unwrapping them with Node's node::ObjectWrap::Unwrap helper function.\nIn the following addon.cc we introduce a function add() that can take on two\nMyObject objects:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nHandle<Value> CreateObject(const Arguments& args) {\n  HandleScope scope;\n  return scope.Close(MyObject::NewInstance(args));\n}\n\nHandle<Value> Add(const Arguments& args) {\n  HandleScope scope;\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  return scope.Close(Number::New(sum));\n}\n\nvoid InitAll(Handle<Object> exports) {\n  MyObject::Init();\n\n  exports->Set(String::NewSymbol("createObject"),\n      FunctionTemplate::New(CreateObject)->GetFunction());\n\n  exports->Set(String::NewSymbol("add"),\n      FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
\n

To make things interesting we introduce a public method in myobject.h so we\ncan probe private values after unwrapping the object:\n\n

\n
#define BUILDING_NODE_EXTENSION\n#ifndef MYOBJECT_H\n#define MYOBJECT_H\n\n#include <node.h>\n\nclass MyObject : public node::ObjectWrap {\n public:\n  static void Init();\n  static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);\n  double Value() const { return value_; }\n\n private:\n  explicit MyObject(double value = 0);\n  ~MyObject();\n\n  static v8::Handle<v8::Value> New(const v8::Arguments& args);\n  static v8::Persistent<v8::Function> constructor;\n  double value_;\n};\n\n#endif
\n

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

\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nPersistent<Function> MyObject::constructor;\n\nMyObject::MyObject(double value) : value_(value) {\n}\n\nMyObject::~MyObject() {\n}\n\nvoid MyObject::Init() {\n  // Prepare constructor template\n  Local<FunctionTemplate> tpl = FunctionTemplate::New(New);\n  tpl->SetClassName(String::NewSymbol("MyObject"));\n  tpl->InstanceTemplate()->SetInternalFieldCount(1);\n  constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n  HandleScope scope;\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    return 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    return scope.Close(constructor->NewInstance(argc, argv));\n  }\n}\n\nHandle<Value> MyObject::NewInstance(const Arguments& args) {\n  HandleScope scope;\n\n  const unsigned argc = 1;\n  Handle<Value> argv[argc] = { args[0] };\n  Local<Object> instance = constructor->NewInstance(argc, argv);\n\n  return scope.Close(instance);\n}
\n

Test it with:\n\n

\n
var addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject(10);\nvar obj2 = addon.createObject(20);\nvar result = addon.add(obj1, obj2);\n\nconsole.log(result); // 30
\n", "type": "module", "displayName": "Passing wrapped objects around" } ], "type": "module", "displayName": "Addon patterns" } ], "type": "module", "displayName": "Addons" }, { "textRaw": "util", "name": "util", "stability": 4, "stabilityText": "API Frozen", "desc": "

These functions are in the module 'util'. Use require('util') to access\nthem.\n\n\n

\n", "methods": [ { "textRaw": "util.format(format, [...])", "type": "method", "name": "format", "desc": "

Returns a formatted string using the first argument as a printf-like format.\n\n

\n

The first argument is a string that contains zero or more placeholders.\nEach placeholder is replaced with the converted value from its corresponding\nargument. Supported placeholders are:\n\n

\n\n

If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.\n\n

\n
util.format('%s:%s', 'foo'); // 'foo:%s'
\n

If there are more arguments than placeholders, the extra arguments are\nconverted to strings with util.inspect() and these strings are concatenated,\ndelimited by a space.\n\n

\n
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
\n

If the first argument is not a format string then util.format() returns\na string that is the concatenation of all its arguments separated by spaces.\nEach argument is converted to a string with util.inspect().\n\n

\n
util.format(1, 2, 3); // '1 2 3'
\n", "signatures": [ { "params": [ { "name": "format" }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.debug(string)", "type": "method", "name": "debug", "desc": "

A synchronous output function. Will block the process and\noutput string immediately to stderr.\n\n

\n
require('util').debug('message on stderr');
\n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "util.error([...])", "type": "method", "name": "error", "desc": "

Same as util.debug() except this will output all arguments immediately to\nstderr.\n\n

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

A synchronous output function. Will block the process and output all arguments\nto stdout with newlines after each argument.\n\n

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

A synchronous output function. Will block the process, cast each argument to a\nstring then output to stdout. Does not place newlines after each argument.\n\n

\n", "signatures": [ { "params": [ { "name": "...", "optional": true } ] } ] }, { "textRaw": "util.log(string)", "type": "method", "name": "log", "desc": "

Output with timestamp on stdout.\n\n

\n
require('util').log('Timestamped message.');
\n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "util.inspect(object, [options])", "type": "method", "name": "inspect", "desc": "

Return a string representation of object, which is useful for debugging.\n\n

\n

An optional options object may be passed that alters certain aspects of the\nformatted string:\n\n

\n\n

Example of inspecting all properties of the util object:\n\n

\n
var util = require('util');\n\nconsole.log(util.inspect(util, { showHidden: true, depth: null }));
\n", "modules": [ { "textRaw": "Customizing `util.inspect` colors", "name": "customizing_`util.inspect`_colors", "desc": "

Color output (if enabled) of util.inspect is customizable globally\nvia util.inspect.styles and util.inspect.colors objects.\n\n

\n

util.inspect.styles is a map assigning each style a color\nfrom util.inspect.colors.\nHighlighted styles and their default values are:\n number (yellow)\n boolean (yellow)\n string (green)\n date (magenta)\n regexp (red)\n null (bold)\n undefined (grey)\n special - only function at this time (cyan)\n * name (intentionally no styling)\n\n

\n

Predefined color codes are: white, grey, black, blue, cyan, \ngreen, magenta, red and yellow.\nThere are also bold, italic, underline and inverse codes.\n\n

\n

Objects also may define their own inspect(depth) function which util.inspect()\nwill invoke and use the result of when inspecting the object:\n\n

\n
var util = require('util');\n\nvar obj = { name: 'nate' };\nobj.inspect = function(depth) {\n  return '{' + this.name + '}';\n};\n\nutil.inspect(obj);\n  // "{nate}"
\n", "type": "module", "displayName": "Customizing `util.inspect` colors" } ], "signatures": [ { "params": [ { "name": "object" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "util.isArray(object)", "type": "method", "name": "isArray", "desc": "

Returns true if the given "object" is an Array. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isArray([])\n  // true\nutil.isArray(new Array)\n  // true\nutil.isArray({})\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isRegExp(object)", "type": "method", "name": "isRegExp", "desc": "

Returns true if the given "object" is a RegExp. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isRegExp(/some regexp/)\n  // true\nutil.isRegExp(new RegExp('another regexp'))\n  // true\nutil.isRegExp({})\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isDate(object)", "type": "method", "name": "isDate", "desc": "

Returns true if the given "object" is a Date. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isDate(new Date())\n  // true\nutil.isDate(Date())\n  // false (without 'new' returns a String)\nutil.isDate({})\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.isError(object)", "type": "method", "name": "isError", "desc": "

Returns true if the given "object" is an Error. false otherwise.\n\n

\n
var util = require('util');\n\nutil.isError(new Error())\n  // true\nutil.isError(new TypeError())\n  // true\nutil.isError({ name: 'Error', message: 'an error occurred' })\n  // false
\n", "signatures": [ { "params": [ { "name": "object" } ] } ] }, { "textRaw": "util.pump(readableStream, writableStream, [callback])", "type": "method", "name": "pump", "stability": 0, "stabilityText": "Deprecated: Use readableStream.pipe(writableStream)", "desc": "

Read the data from readableStream and send it to the writableStream.\nWhen writableStream.write(data) returns false readableStream will be\npaused until the drain event occurs on the writableStream. callback gets\nan error as its only argument and is called when writableStream is closed or\nwhen an error occurs.\n\n\n

\n", "signatures": [ { "params": [ { "name": "readableStream" }, { "name": "writableStream" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "util.inherits(constructor, superConstructor)", "type": "method", "name": "inherits", "desc": "

Inherit the prototype methods from one\nconstructor\ninto another. The prototype of constructor will be set to a new\nobject created from superConstructor.\n\n

\n

As an additional convenience, superConstructor will be accessible\nthrough the constructor.super_ property.\n\n

\n
var util = require("util");\nvar events = require("events");\n\nfunction MyStream() {\n    events.EventEmitter.call(this);\n}\n\nutil.inherits(MyStream, events.EventEmitter);\n\nMyStream.prototype.write = function(data) {\n    this.emit("data", data);\n}\n\nvar stream = new MyStream();\n\nconsole.log(stream instanceof events.EventEmitter); // true\nconsole.log(MyStream.super_ === events.EventEmitter); // true\n\nstream.on("data", function(data) {\n    console.log('Received data: "' + data + '"');\n})\nstream.write("It works!"); // Received data: "It works!"
\n", "signatures": [ { "params": [ { "name": "constructor" }, { "name": "superConstructor" } ] } ] } ], "type": "module", "displayName": "util" }, { "textRaw": "Events", "name": "Events", "stability": 4, "stabilityText": "API Frozen", "type": "module", "desc": "

Many objects in Node emit events: a net.Server emits an event each time\na peer connects to it, a fs.readStream emits an event when the file is\nopened. All objects which emit events are instances of events.EventEmitter.\nYou can access this module by doing: require("events");\n\n

\n

Typically, event names are represented by a camel-cased string, however,\nthere aren't any strict restrictions on that, as any string will be accepted.\n\n

\n

Functions can then be attached to objects, to be executed when an event\nis emitted. These functions are called listeners. Inside a listener\nfunction, this refers to the EventEmitter that the listener was\nattached to.\n\n\n

\n", "classes": [ { "textRaw": "Class: events.EventEmitter", "type": "class", "name": "events.EventEmitter", "desc": "

To access the EventEmitter class, require('events').EventEmitter.\n\n

\n

When an EventEmitter instance experiences an error, the typical action is\nto emit an 'error' event. Error events are treated as a special case in node.\nIf there is no listener for it, then the default action is to print a stack\ntrace and exit the program.\n\n

\n

All EventEmitters emit the event 'newListener' when new listeners are\nadded and 'removeListener' when a listener is removed.\n\n

\n", "methods": [ { "textRaw": "emitter.addListener(event, listener)", "type": "method", "name": "addListener", "desc": "

Adds a listener to the end of the listeners array for the specified event.\nNo checks are made to see if the listener has already been added. Multiple\ncalls passing the same combination of event and listener will result in the\nlistener being added multiple times.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
\n

Returns emitter, so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] }, { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.on(event, listener)", "type": "method", "name": "on", "desc": "

Adds a listener to the end of the listeners array for the specified event.\nNo checks are made to see if the listener has already been added. Multiple\ncalls passing the same combination of event and listener will result in the\nlistener being added multiple times.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});
\n

Returns emitter, so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.once(event, listener)", "type": "method", "name": "once", "desc": "

Adds a one time listener for the event. This listener is\ninvoked only the next time the event is fired, after which\nit is removed.\n\n

\n
server.once('connection', function (stream) {\n  console.log('Ah, we have our first user!');\n});
\n

Returns emitter, so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.removeListener(event, listener)", "type": "method", "name": "removeListener", "desc": "

Remove a listener from the listener array for the specified event.\nCaution: changes array indices in the listener array behind the listener.\n\n

\n
var callback = function(stream) {\n  console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);
\n

removeListener will remove, at most, one instance of a listener from the\nlistener array. If any single listener has been added multiple times to the\nlistener array for the specified event, then removeListener must be called\nmultiple times to remove each instance.\n\n

\n

Returns emitter, so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "event" }, { "name": "listener" } ] } ] }, { "textRaw": "emitter.removeAllListeners([event])", "type": "method", "name": "removeAllListeners", "desc": "

Removes all listeners, or those of the specified event. It's not a good idea to\nremove listeners that were added elsewhere in the code, especially when it's on\nan emitter that you didn't create (e.g. sockets or file streams).\n\n

\n

Returns emitter, so calls can be chained.\n\n

\n", "signatures": [ { "params": [ { "name": "event", "optional": true } ] } ] }, { "textRaw": "emitter.setMaxListeners(n)", "type": "method", "name": "setMaxListeners", "desc": "

By default EventEmitters will print a warning if more than 10 listeners are\nadded for a particular event. This is a useful default which helps finding memory leaks.\nObviously not all Emitters should be limited to 10. This function allows\nthat to be increased. Set to zero for unlimited.\n\n\n

\n", "signatures": [ { "params": [ { "name": "n" } ] } ] }, { "textRaw": "emitter.listeners(event)", "type": "method", "name": "listeners", "desc": "

Returns an array of listeners for the specified event.\n\n

\n
server.on('connection', function (stream) {\n  console.log('someone connected!');\n});\nconsole.log(util.inspect(server.listeners('connection'))); // [ [Function] ]
\n", "signatures": [ { "params": [ { "name": "event" } ] } ] }, { "textRaw": "emitter.emit(event, [arg1], [arg2], [...])", "type": "method", "name": "emit", "desc": "

Execute each of the listeners in order with the supplied arguments.\n\n

\n

Returns true if event had listeners, false otherwise.\n\n\n

\n", "signatures": [ { "params": [ { "name": "event" }, { "name": "arg1", "optional": true }, { "name": "arg2", "optional": true }, { "name": "...", "optional": true } ] } ] } ], "classMethods": [ { "textRaw": "Class Method: EventEmitter.listenerCount(emitter, event)", "type": "classMethod", "name": "listenerCount", "desc": "

Return the number of listeners for a given event.\n\n\n

\n", "signatures": [ { "params": [ { "name": "emitter" }, { "name": "event" } ] } ] } ], "events": [ { "textRaw": "Event: 'newListener'", "type": "event", "name": "newListener", "params": [], "desc": "

This event is emitted any time a listener is added. When this event is triggered,\nthe listener may not yet have been added to the array of listeners for the event.\n\n\n

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

This event is emitted any time someone removes a listener. When this event is triggered,\nthe listener may not yet have been removed from the array of listeners for the event.\n\n

\n" } ] } ] }, { "textRaw": "Domain", "name": "domain", "stability": 2, "stabilityText": "Unstable", "desc": "

Domains provide a way to handle multiple different IO operations as a\nsingle group. If any of the event emitters or callbacks registered to a\ndomain emit an error event, or throw an error, then the domain object\nwill be notified, rather than losing the context of the error in the\nprocess.on('uncaughtException') handler, or causing the program to\nexit immediately with an error code.\n\n

\n", "miscs": [ { "textRaw": "Warning: Don't Ignore Errors!", "name": "Warning: Don't Ignore Errors!", "type": "misc", "desc": "

Domain error handlers are not a substitute for closing down your\nprocess when an error occurs.\n\n

\n

By the very nature of how throw works in JavaScript, there is almost\nnever any way to safely "pick up where you left off", without leaking\nreferences, or creating some other sort of undefined brittle state.\n\n

\n

The safest way to respond to a thrown error is to shut down the\nprocess. Of course, in a normal web server, you might have many\nconnections open, and it is not reasonable to abruptly shut those down\nbecause an error was triggered by someone else.\n\n

\n

The better approach is send an error response to the request that\ntriggered the error, while letting the others finish in their normal\ntime, and stop listening for new requests in that worker.\n\n

\n

In this way, domain usage goes hand-in-hand with the cluster module,\nsince the master process can fork a new worker when a worker\nencounters an error. For node programs that scale to multiple\nmachines, the terminating proxy or service registry can take note of\nthe failure, and react accordingly.\n\n

\n

For example, this is not a good idea:\n\n

\n
// XXX WARNING!  BAD IDEA!\n\nvar d = require('domain').create();\nd.on('error', function(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(function() {\n  require('http').createServer(function(req, res) {\n    handleRequest(req, res);\n  }).listen(PORT);\n});
\n

By using the context of a domain, and the resilience of separating our\nprogram into multiple worker processes, we can react more\nappropriately, and handle errors with much greater safety.\n\n

\n
// Much better!\n\nvar cluster = require('cluster');\nvar 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', function(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  var 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  var server = require('http').createServer(function(req, res) {\n    var d = domain.create();\n    d.on('error', function(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(function() {\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(function() {\n      handleRequest(req, res);\n    });\n  });\n  server.listen(PORT);\n}\n\n// This part isn't important.  Just an example routing thing.\n// You'd put your fancy application logic here.\nfunction handleRequest(req, res) {\n  switch(req.url) {\n    case '/error':\n      // We do some async stuff, and then...\n      setTimeout(function() {\n        // Whoops!\n        flerb.bark();\n      });\n      break;\n    default:\n      res.end('ok');\n  }\n}
\n" }, { "textRaw": "Additions to Error objects", "name": "Additions to Error objects", "type": "misc", "desc": "

Any time an Error object is routed through a domain, a few extra fields\nare added to it.\n\n

\n\n" }, { "textRaw": "Implicit Binding", "name": "Implicit Binding", "type": "misc", "desc": "

If domains are in use, then all new EventEmitter objects (including\nStream objects, requests, responses, etc.) will be implicitly bound to\nthe active domain at the time of their creation.\n\n

\n

Additionally, callbacks passed to lowlevel event loop requests (such as\nto fs.open, or other callback-taking methods) will automatically be\nbound to the active domain. If they throw, then the domain will catch\nthe error.\n\n

\n

In order to prevent excessive memory usage, Domain objects themselves\nare not implicitly added as children of the active domain. If they\nwere, then it would be too easy to prevent request and response objects\nfrom being properly garbage collected.\n\n

\n

If you want to nest Domain objects as children of a parent Domain,\nthen you must explicitly add them.\n\n

\n

Implicit binding routes thrown errors and 'error' events to the\nDomain's error event, but does not register the EventEmitter on the\nDomain, so domain.dispose() will not shut down the EventEmitter.\nImplicit binding only takes care of thrown errors and 'error' events.\n\n

\n" }, { "textRaw": "Explicit Binding", "name": "Explicit Binding", "type": "misc", "desc": "

Sometimes, the domain in use is not the one that ought to be used for a\nspecific event emitter. Or, the event emitter could have been created\nin the context of one domain, but ought to instead be bound to some\nother domain.\n\n

\n

For example, there could be one domain in use for an HTTP server, but\nperhaps we would like to have a separate domain to use for each request.\n\n

\n

That is possible via explicit binding.\n\n

\n

For example:\n\n

\n
// create a top-level domain for the server\nvar serverDomain = domain.create();\n\nserverDomain.run(function() {\n  // server is created in the scope of serverDomain\n  http.createServer(function(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', function(er) {\n      console.error('Error', er, req.url);\n      try {\n        res.writeHead(500);\n        res.end('Error occurred, sorry.');\n      } catch (er) {\n        console.error('Error sending 500', er, req.url);\n      }\n    });\n  }).listen(1337);\n});
\n" } ], "methods": [ { "textRaw": "domain.create()", "type": "method", "name": "create", "signatures": [ { "return": { "textRaw": "return: {Domain} ", "name": "return", "type": "Domain" }, "params": [] }, { "params": [] } ], "desc": "

Returns a new Domain object.\n\n

\n" } ], "classes": [ { "textRaw": "Class: Domain", "type": "class", "name": "Domain", "desc": "

The Domain class encapsulates the functionality of routing errors and\nuncaught exceptions to the active Domain object.\n\n

\n

Domain is a child class of [EventEmitter][]. To handle the errors that it\ncatches, listen to its error event.\n\n

\n", "methods": [ { "textRaw": "domain.run(fn)", "type": "method", "name": "run", "signatures": [ { "params": [ { "textRaw": "`fn` {Function} ", "name": "fn", "type": "Function" } ] }, { "params": [ { "name": "fn" } ] } ], "desc": "

Run the supplied function in the context of the domain, implicitly\nbinding all event emitters, timers, and lowlevel requests that are\ncreated in that context.\n\n

\n

This is the most basic way to use a domain.\n\n

\n

Example:\n\n

\n
var d = domain.create();\nd.on('error', function(er) {\n  console.error('Caught error!', er);\n});\nd.run(function() {\n  process.nextTick(function() {\n    setTimeout(function() { // simulating some various async stuff\n      fs.open('non-existent file', 'r', function(er, fd) {\n        if (er) throw er;\n        // proceed...\n      });\n    }, 100);\n  });\n});
\n

In this example, the d.on('error') handler will be triggered, rather\nthan crashing the program.\n\n

\n" }, { "textRaw": "domain.add(emitter)", "type": "method", "name": "add", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be added to the domain ", "name": "emitter", "type": "EventEmitter | Timer", "desc": "emitter or timer to be added to the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

Explicitly adds an emitter to the domain. If any event handlers called by\nthe emitter throw an error, or if the emitter emits an error event, it\nwill be routed to the domain's error event, just like with implicit\nbinding.\n\n

\n

This also works with timers that are returned from setInterval and\nsetTimeout. If their callback function throws, it will be caught by\nthe domain 'error' handler.\n\n

\n

If the Timer or EventEmitter was already bound to a domain, it is removed\nfrom that one, and bound to this one instead.\n\n

\n" }, { "textRaw": "domain.remove(emitter)", "type": "method", "name": "remove", "signatures": [ { "params": [ { "textRaw": "`emitter` {EventEmitter | Timer} emitter or timer to be removed from the domain ", "name": "emitter", "type": "EventEmitter | Timer", "desc": "emitter or timer to be removed from the domain" } ] }, { "params": [ { "name": "emitter" } ] } ], "desc": "

The opposite of domain.add(emitter). Removes domain handling from the\nspecified emitter.\n\n

\n" }, { "textRaw": "domain.bind(callback)", "type": "method", "name": "bind", "signatures": [ { "return": { "textRaw": "return: {Function} The bound function ", "name": "return", "type": "Function", "desc": "The bound function" }, "params": [ { "textRaw": "`callback` {Function} The callback function ", "name": "callback", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

The returned function will be a wrapper around the supplied callback\nfunction. When the returned function is called, any errors that are\nthrown will be routed to the domain's error event.\n\n

\n

Example

\n
var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.bind(function(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', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
\n" }, { "textRaw": "domain.intercept(callback)", "type": "method", "name": "intercept", "signatures": [ { "return": { "textRaw": "return: {Function} The intercepted function ", "name": "return", "type": "Function", "desc": "The intercepted function" }, "params": [ { "textRaw": "`callback` {Function} The callback function ", "name": "callback", "type": "Function", "desc": "The callback function" } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

This method is almost identical to domain.bind(callback). However, in\naddition to catching thrown errors, it will also intercept Error\nobjects sent as the first argument to the function.\n\n

\n

In this way, the common if (er) return callback(er); pattern can be replaced\nwith a single error handler in a single place.\n\n

\n

Example

\n
var d = domain.create();\n\nfunction readSomeFile(filename, cb) {\n  fs.readFile(filename, 'utf8', d.intercept(function(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', function(er) {\n  // an error occurred somewhere.\n  // if we throw it now, it will crash the program\n  // with the normal line number and stack message.\n});
\n" }, { "textRaw": "domain.enter()", "type": "method", "name": "enter", "desc": "

The enter method is plumbing used by the run, bind, and intercept\nmethods to set the active domain. It sets domain.active and process.domain\nto the domain, and implicitly pushes the domain onto the domain stack managed\nby the domain module (see domain.exit() for details on the domain stack). The\ncall to enter delimits the beginning of a chain of asynchronous calls and I/O\noperations bound to a domain.\n\n

\n

Calling enter changes only the active domain, and does not alter the domain\nitself. Enter and exit can be called an arbitrary number of times on a\nsingle domain.\n\n

\n

If the domain on which enter is called has been disposed, enter will return\nwithout setting the domain.\n\n

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

The exit method exits the current domain, popping it off the domain stack.\nAny time execution is going to switch to the context of a different chain of\nasynchronous calls, it's important to ensure that the current domain is exited.\nThe call to exit delimits either the end of or an interruption to the chain\nof asynchronous calls and I/O operations bound to a domain.\n\n

\n

If there are multiple, nested domains bound to the current execution context,\nexit will exit any domains nested within this domain.\n\n

\n

Calling exit changes only the active domain, and does not alter the domain\nitself. Enter and exit can be called an arbitrary number of times on a\nsingle domain.\n\n

\n

If the domain on which exit is called has been disposed, exit will return\nwithout exiting the domain.\n\n

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

The dispose method destroys a domain, and makes a best effort attempt to\nclean up any and all IO that is associated with the domain. Streams are\naborted, ended, closed, and/or destroyed. Timers are cleared.\nExplicitly bound callbacks are no longer called. Any error events that\nare raised as a result of this are ignored.\n\n

\n

The intention of calling dispose is generally to prevent cascading\nerrors when a critical part of the Domain context is found to be in an\nerror state.\n\n

\n

Once the domain is disposed the dispose event will emit.\n\n

\n

Note that IO might still be performed. However, to the highest degree\npossible, once a domain is disposed, further errors from the emitters in\nthat set will be ignored. So, even if some remaining actions are still\nin flight, Node.js will not communicate further about them.\n\n

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

An array of timers and event emitters that have been explicitly added\nto the domain.\n\n

\n" } ] } ], "type": "module", "displayName": "Domain" }, { "textRaw": "Buffer", "name": "buffer", "stability": 3, "stabilityText": "Stable", "desc": "

Pure JavaScript is Unicode friendly but not nice to binary data. When\ndealing with TCP streams or the file system, it's necessary to handle octet\nstreams. Node has several strategies for manipulating, creating, and\nconsuming octet streams.\n\n

\n

Raw data is stored in instances of the Buffer class. A Buffer is similar\nto an array of integers but corresponds to a raw memory allocation outside\nthe V8 heap. A Buffer cannot be resized.\n\n

\n

The Buffer class is a global, making it very rare that one would need\nto ever require('buffer').\n\n

\n

Converting between Buffers and JavaScript string objects requires an explicit\nencoding method. Here are the different string encodings.\n\n

\n\n

Creating a typed array from a Buffer works with the following caveats:\n\n

\n
    \n
  1. The buffer's memory is copied, not shared.

    \n
  2. \n
  3. The buffer's memory is interpreted as an array, not a byte array. That is,\nnew Uint32Array(new Buffer([1,2,3,4])) creates a 4-element Uint32Array\nwith elements [1,2,3,4], not an Uint32Array with a single element\n[0x1020304] or [0x4030201].

    \n
  4. \n
\n

NOTE: Node.js v0.8 simply retained a reference to the buffer in array.buffer\ninstead of cloning it.\n\n

\n

While more efficient, it introduces subtle incompatibilities with the typed\narrays specification. ArrayBuffer#slice() makes a copy of the slice while\nBuffer#slice() creates a view.\n\n

\n", "classes": [ { "textRaw": "Class: Buffer", "type": "class", "name": "Buffer", "desc": "

The Buffer class is a global type for dealing with binary data directly.\nIt can be constructed in a variety of ways.\n\n

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

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

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

Tests if obj is a Buffer.\n\n

\n" }, { "textRaw": "Class Method: Buffer.byteLength(string, [encoding])", "type": "classMethod", "name": "byteLength", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`string` String ", "name": "string", "desc": "String" }, { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "encoding", "optional": true } ] } ], "desc": "

Gives the actual byte length of a string. encoding defaults to 'utf8'.\nThis is not the same as String.prototype.length since that returns the\nnumber of characters in a string.\n\n

\n

Example:\n\n

\n
str = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(str + ": " + str.length + " characters, " +\n  Buffer.byteLength(str, 'utf8') + " bytes");\n\n// ½ + ¼ = ¾: 9 characters, 12 bytes
\n" }, { "textRaw": "Class Method: Buffer.concat(list, [totalLength])", "type": "classMethod", "name": "concat", "signatures": [ { "params": [ { "textRaw": "`list` {Array} List of Buffer objects to concat ", "name": "list", "type": "Array", "desc": "List of Buffer objects to concat" }, { "textRaw": "`totalLength` {Number} Total length of the buffers when concatenated ", "name": "totalLength", "type": "Number", "desc": "Total length of the buffers when concatenated", "optional": true } ] }, { "params": [ { "name": "list" }, { "name": "totalLength", "optional": true } ] } ], "desc": "

Returns a buffer which is the result of concatenating all the buffers in\nthe list together.\n\n

\n

If the list has no items, or if the totalLength is 0, then it returns a\nzero-length buffer.\n\n

\n

If the list has exactly one item, then the first item of the list is\nreturned.\n\n

\n

If the list has more than one item, then a new Buffer is created.\n\n

\n

If totalLength is not provided, it is read from the buffers in the list.\nHowever, this adds an additional loop to the function, so it is faster\nto provide the length explicitly.\n\n

\n" } ], "methods": [ { "textRaw": "buf.write(string, [offset], [length], [encoding])", "type": "method", "name": "write", "signatures": [ { "params": [ { "textRaw": "`string` String - data to be written to buffer ", "name": "string", "desc": "String - data to be written to buffer" }, { "textRaw": "`offset` Number, Optional, Default: 0 ", "name": "offset", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`length` Number, Optional, Default: `buffer.length - offset` ", "name": "length", "desc": "Number, Optional, Default: `buffer.length - offset`", "optional": true }, { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true } ] }, { "params": [ { "name": "string" }, { "name": "offset", "optional": true }, { "name": "length", "optional": true }, { "name": "encoding", "optional": true } ] } ], "desc": "

Writes string to the buffer at offset using the given encoding.\noffset defaults to 0, encoding defaults to 'utf8'. length is\nthe number of bytes to write. Returns number of octets written. If buffer did\nnot contain enough space to fit the entire string, it will write a partial\namount of the string. length defaults to buffer.length - offset.\nThe method will not write partial characters.\n\n

\n
buf = new Buffer(256);\nlen = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\nconsole.log(len + " bytes: " + buf.toString('utf8', 0, len));
\n

The number of characters written (which may be different than the number of\nbytes written) is set in Buffer._charsWritten and will be overwritten the\nnext time buf.write() is called.\n\n\n

\n" }, { "textRaw": "buf.toString([encoding], [start], [end])", "type": "method", "name": "toString", "signatures": [ { "params": [ { "textRaw": "`encoding` String, Optional, Default: 'utf8' ", "name": "encoding", "desc": "String, Optional, Default: 'utf8'", "optional": true }, { "textRaw": "`start` Number, Optional, Default: 0 ", "name": "start", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`end` Number, Optional, Default: `buffer.length` ", "name": "end", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "encoding", "optional": true }, { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

Decodes and returns a string from buffer data encoded using the specified\ncharacter set encoding. If encoding is undefined or null, then encoding\ndefaults to 'utf8'. The start and end parameters default to 0 and\nbuffer.length when undefined`.\n\n

\n
buf = new Buffer(26);\nfor (var i = 0 ; i < 26 ; i++) {\n  buf[i] = i + 97; // 97 is ASCII a\n}\nbuf.toString('ascii'); // outputs: abcdefghijklmnopqrstuvwxyz\nbuf.toString('ascii',0,5); // outputs: abcde\nbuf.toString('utf8',0,5); // outputs: abcde\nbuf.toString(undefined,0,5); // encoding defaults to 'utf8', outputs abcde
\n

See buffer.write() example, above.\n\n\n

\n" }, { "textRaw": "buf.toJSON()", "type": "method", "name": "toJSON", "desc": "

Returns a JSON-representation of the Buffer instance, which is identical to the\noutput for JSON Arrays. JSON.stringify implicitly calls this function when\nstringifying a Buffer instance.\n\n

\n

Example:\n\n

\n
var buf = new Buffer('test');\nvar json = JSON.stringify(buf);\n\nconsole.log(json);\n// '[116,101,115,116]'\n\nvar copy = new Buffer(JSON.parse(json));\n\nconsole.log(copy);\n// <Buffer 74 65 73 74>
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])", "type": "method", "name": "copy", "signatures": [ { "params": [ { "textRaw": "`targetBuffer` Buffer object - Buffer to copy into ", "name": "targetBuffer", "desc": "Buffer object - Buffer to copy into" }, { "textRaw": "`targetStart` Number, Optional, Default: 0 ", "name": "targetStart", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`sourceStart` Number, Optional, Default: 0 ", "name": "sourceStart", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`sourceEnd` Number, Optional, Default: `buffer.length` ", "name": "sourceEnd", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "targetBuffer" }, { "name": "targetStart", "optional": true }, { "name": "sourceStart", "optional": true }, { "name": "sourceEnd", "optional": true } ] } ], "desc": "

Copies data from a region of this buffer to a region in the target buffer even\nif the target memory region overlaps with the source. If undefined the\ntargetStart and sourceStart parameters default to 0 while sourceEnd\ndefaults to buffer.length.\n\n

\n

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

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

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

\n
buf = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf[i] = i + 97; // 97 is ASCII a\n}\n\nbuf.copy(buf, 0, 4, 10);\nconsole.log(buf.toString());\n\n// efghijghijklmnopqrstuvwxyz
\n" }, { "textRaw": "buf.slice([start], [end])", "type": "method", "name": "slice", "signatures": [ { "params": [ { "textRaw": "`start` Number, Optional, Default: 0 ", "name": "start", "desc": "Number, Optional, Default: 0", "optional": true }, { "textRaw": "`end` Number, Optional, Default: `buffer.length` ", "name": "end", "desc": "Number, Optional, Default: `buffer.length`", "optional": true } ] }, { "params": [ { "name": "start", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

Returns a new buffer which references the same memory as the old, but offset\nand cropped by the start (defaults to 0) and end (defaults to\nbuffer.length) indexes. Negative indexes start from the end of the buffer.\n\n

\n

Modifying the new buffer slice will modify memory in the original buffer!\n\n

\n

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

\n
var buf1 = new Buffer(26);\n\nfor (var i = 0 ; i < 26 ; i++) {\n  buf1[i] = i + 97; // 97 is ASCII a\n}\n\nvar buf2 = buf1.slice(0, 3);\nconsole.log(buf2.toString('ascii', 0, buf2.length));\nbuf1[0] = 33;\nconsole.log(buf2.toString('ascii', 0, buf2.length));\n\n// abc\n// !bc
\n" }, { "textRaw": "buf.readUInt8(offset, [noAssert])", "type": "method", "name": "readUInt8", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nfor (ii = 0; ii < buf.length; ii++) {\n  console.log(buf.readUInt8(ii));\n}\n\n// 0x3\n// 0x4\n// 0x23\n// 0x42
\n" }, { "textRaw": "buf.readUInt16LE(offset, [noAssert])", "type": "method", "name": "readUInt16LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
\n" }, { "textRaw": "buf.readUInt16BE(offset, [noAssert])", "type": "method", "name": "readUInt16BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt16BE(0));\nconsole.log(buf.readUInt16LE(0));\nconsole.log(buf.readUInt16BE(1));\nconsole.log(buf.readUInt16LE(1));\nconsole.log(buf.readUInt16BE(2));\nconsole.log(buf.readUInt16LE(2));\n\n// 0x0304\n// 0x0403\n// 0x0423\n// 0x2304\n// 0x2342\n// 0x4223
\n" }, { "textRaw": "buf.readUInt32LE(offset, [noAssert])", "type": "method", "name": "readUInt32LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

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

Reads an unsigned 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x3;\nbuf[1] = 0x4;\nbuf[2] = 0x23;\nbuf[3] = 0x42;\n\nconsole.log(buf.readUInt32BE(0));\nconsole.log(buf.readUInt32LE(0));\n\n// 0x03042342\n// 0x42230403
\n" }, { "textRaw": "buf.readInt8(offset, [noAssert])", "type": "method", "name": "readInt8", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

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

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt8, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" }, { "textRaw": "buf.readInt16LE(offset, [noAssert])", "type": "method", "name": "readInt16LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" }, { "textRaw": "buf.readInt16BE(offset, [noAssert])", "type": "method", "name": "readInt16BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt16*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" }, { "textRaw": "buf.readInt32LE(offset, [noAssert])", "type": "method", "name": "readInt32LE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" }, { "textRaw": "buf.readInt32BE(offset, [noAssert])", "type": "method", "name": "readInt32BE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Works as buffer.readUInt32*, except buffer contents are treated as two's\ncomplement signed values.\n\n

\n" }, { "textRaw": "buf.readFloatLE(offset, [noAssert])", "type": "method", "name": "readFloatLE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
\n" }, { "textRaw": "buf.readFloatBE(offset, [noAssert])", "type": "method", "name": "readFloatBE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(4);\n\nbuf[0] = 0x00;\nbuf[1] = 0x00;\nbuf[2] = 0x80;\nbuf[3] = 0x3f;\n\nconsole.log(buf.readFloatLE(0));\n\n// 0x01
\n" }, { "textRaw": "buf.readDoubleLE(offset, [noAssert])", "type": "method", "name": "readDoubleLE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
\n" }, { "textRaw": "buf.readDoubleBE(offset, [noAssert])", "type": "method", "name": "readDoubleBE", "signatures": [ { "return": { "textRaw": "Return: Number ", "name": "return", "desc": "Number" }, "params": [ { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Reads a 64 bit double from the buffer at the specified offset with specified\nendian format.\n\n

\n

Set noAssert to true to skip validation of offset. This means that offset\nmay be beyond the end of the buffer. Defaults to false.\n\n

\n

Example:\n\n

\n
var buf = new Buffer(8);\n\nbuf[0] = 0x55;\nbuf[1] = 0x55;\nbuf[2] = 0x55;\nbuf[3] = 0x55;\nbuf[4] = 0x55;\nbuf[5] = 0x55;\nbuf[6] = 0xd5;\nbuf[7] = 0x3f;\n\nconsole.log(buf.readDoubleLE(0));\n\n// 0.3333333333333333
\n" }, { "textRaw": "buf.writeUInt8(value, offset, [noAssert])", "type": "method", "name": "writeUInt8", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset. Note, value must be a\nvalid unsigned 8 bit integer.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt8(0x3, 0);\nbuf.writeUInt8(0x4, 1);\nbuf.writeUInt8(0x23, 2);\nbuf.writeUInt8(0x42, 3);\n\nconsole.log(buf);\n\n// <Buffer 03 04 23 42>
\n" }, { "textRaw": "buf.writeUInt16LE(value, offset, [noAssert])", "type": "method", "name": "writeUInt16LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
\n" }, { "textRaw": "buf.writeUInt16BE(value, offset, [noAssert])", "type": "method", "name": "writeUInt16BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 16 bit integer.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt16BE(0xdead, 0);\nbuf.writeUInt16BE(0xbeef, 2);\n\nconsole.log(buf);\n\nbuf.writeUInt16LE(0xdead, 0);\nbuf.writeUInt16LE(0xbeef, 2);\n\nconsole.log(buf);\n\n// <Buffer de ad be ef>\n// <Buffer ad de ef be>
\n" }, { "textRaw": "buf.writeUInt32LE(value, offset, [noAssert])", "type": "method", "name": "writeUInt32LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
\n" }, { "textRaw": "buf.writeUInt32BE(value, offset, [noAssert])", "type": "method", "name": "writeUInt32BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid unsigned 32 bit integer.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeUInt32BE(0xfeedface, 0);\n\nconsole.log(buf);\n\nbuf.writeUInt32LE(0xfeedface, 0);\n\nconsole.log(buf);\n\n// <Buffer fe ed fa ce>\n// <Buffer ce fa ed fe>
\n" }, { "textRaw": "buf.writeInt8(value, offset, [noAssert])", "type": "method", "name": "writeInt8", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset. Note, value must be a\nvalid signed 8 bit integer.\n\n

\n

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

\n

Works as buffer.writeUInt8, except value is written out as a two's complement\nsigned integer into buffer.\n\n

\n" }, { "textRaw": "buf.writeInt16LE(value, offset, [noAssert])", "type": "method", "name": "writeInt16LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

\n

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

\n

Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" }, { "textRaw": "buf.writeInt16BE(value, offset, [noAssert])", "type": "method", "name": "writeInt16BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 16 bit integer.\n\n

\n

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

\n

Works as buffer.writeUInt16*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" }, { "textRaw": "buf.writeInt32LE(value, offset, [noAssert])", "type": "method", "name": "writeInt32LE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

\n

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

\n

Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" }, { "textRaw": "buf.writeInt32BE(value, offset, [noAssert])", "type": "method", "name": "writeInt32BE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid signed 32 bit integer.\n\n

\n

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

\n

Works as buffer.writeUInt32*, except value is written out as a two's\ncomplement signed integer into buffer.\n\n

\n" }, { "textRaw": "buf.writeFloatLE(value, offset, [noAssert])", "type": "method", "name": "writeFloatLE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, behavior is unspecified if value is not a 32 bit float.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
\n" }, { "textRaw": "buf.writeFloatBE(value, offset, [noAssert])", "type": "method", "name": "writeFloatBE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, behavior is unspecified if value is not a 32 bit float.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(4);\nbuf.writeFloatBE(0xcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeFloatLE(0xcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 4f 4a fe bb>\n// <Buffer bb fe 4a 4f>
\n" }, { "textRaw": "buf.writeDoubleLE(value, offset, [noAssert])", "type": "method", "name": "writeDoubleLE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
\n" }, { "textRaw": "buf.writeDoubleBE(value, offset, [noAssert])", "type": "method", "name": "writeDoubleBE", "signatures": [ { "params": [ { "textRaw": "`value` Number ", "name": "value", "desc": "Number" }, { "textRaw": "`offset` Number ", "name": "offset", "desc": "Number" }, { "textRaw": "`noAssert` Boolean, Optional, Default: false ", "name": "noAssert", "desc": "Boolean, Optional, Default: false", "optional": true } ] }, { "params": [ { "name": "value" }, { "name": "offset" }, { "name": "noAssert", "optional": true } ] } ], "desc": "

Writes value to the buffer at the specified offset with specified endian\nformat. Note, value must be a valid 64 bit double.\n\n

\n

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

\n

Example:\n\n

\n
var buf = new Buffer(8);\nbuf.writeDoubleBE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\nbuf.writeDoubleLE(0xdeadbeefcafebabe, 0);\n\nconsole.log(buf);\n\n// <Buffer 43 eb d5 b7 dd f9 5f d7>\n// <Buffer d7 5f f9 dd b7 d5 eb 43>
\n" }, { "textRaw": "buf.fill(value, [offset], [end])", "type": "method", "name": "fill", "signatures": [ { "params": [ { "textRaw": "`value` ", "name": "value" }, { "textRaw": "`offset` Number, Optional ", "name": "offset", "optional": true, "desc": "Number" }, { "textRaw": "`end` Number, Optional ", "name": "end", "optional": true, "desc": "Number" } ] }, { "params": [ { "name": "value" }, { "name": "offset", "optional": true }, { "name": "end", "optional": true } ] } ], "desc": "

Fills the buffer with the specified value. If the offset (defaults to 0)\nand end (defaults to buffer.length) are not given it will fill the entire\nbuffer.\n\n

\n
var b = new Buffer(50);\nb.fill("h");
\n" } ], "properties": [ { "textRaw": "buf[index]", "name": "[index]", "desc": "

Get and set the octet at index. The values refer to individual bytes,\nso the legal range is between 0x00 and 0xFF hex or 0 and 255.\n\n

\n

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

\n
str = "node.js";\nbuf = new Buffer(str.length);\n\nfor (var i = 0; i < str.length ; i++) {\n  buf[i] = str.charCodeAt(i);\n}\n\nconsole.log(buf);\n\n// node.js
\n" }, { "textRaw": "`length` Number ", "name": "length", "desc": "

The size of the buffer in bytes. Note that this is not necessarily the size\nof the contents. length refers to the amount of memory allocated for the\nbuffer object. It does not change when the contents of the buffer are changed.\n\n

\n
buf = new Buffer(1234);\n\nconsole.log(buf.length);\nbuf.write("some string", 0, "ascii");\nconsole.log(buf.length);\n\n// 1234\n// 1234
\n

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

\n
buf = new Buffer(10);\nbuf.write("abcdefghj", 0, "ascii");\nconsole.log(buf.length); // 10\nbuf = buf.slice(0,5);\nconsole.log(buf.length); // 5
\n", "shortDesc": "Number" } ], "signatures": [ { "params": [ { "textRaw": "`size` Number ", "name": "size", "desc": "Number" } ], "desc": "

Allocates a new buffer of size octets.\n\n

\n" }, { "params": [ { "name": "size" } ], "desc": "

Allocates a new buffer of size octets.\n\n

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

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

\n" }, { "params": [ { "name": "array" } ], "desc": "

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

\n" }, { "params": [ { "textRaw": "`str` String - string to encode. ", "name": "str", "desc": "String - string to encode." }, { "textRaw": "`encoding` String - encoding to use, Optional. ", "name": "encoding", "desc": "String - encoding to use, Optional.", "optional": true } ], "desc": "

Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

\n" }, { "params": [ { "name": "str" }, { "name": "encoding", "optional": true } ], "desc": "

Allocates a new buffer containing the given str.\nencoding defaults to 'utf8'.\n\n

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

This class is primarily for internal use. JavaScript programs should\nuse Buffer instead of using SlowBuffer.\n\n

\n

In order to avoid the overhead of allocating many C++ Buffer objects for\nsmall blocks of memory in the lifetime of a server, Node allocates memory\nin 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it\nwill be backed by a parent SlowBuffer object. If it is larger than this,\nthen Node will allocate a SlowBuffer slab for it directly.\n\n

\n" } ], "properties": [ { "textRaw": "`INSPECT_MAX_BYTES` Number, Default: 50 ", "name": "INSPECT_MAX_BYTES", "desc": "

How many bytes will be returned when buffer.inspect() is called. This can\nbe overridden by user modules.\n\n

\n

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

\n", "shortDesc": "Number, Default: 50" } ], "type": "module", "displayName": "Buffer" }, { "textRaw": "Stream", "name": "stream", "stability": 2, "stabilityText": "Unstable", "desc": "

A stream is an abstract interface implemented by various objects in\nNode. For example a request to an HTTP\nserver is a stream, as is\n[stdout][]. Streams are readable, writable, or both. All streams are\ninstances of [EventEmitter][]\n\n

\n

You can load the Stream base classes by doing require('stream').\nThere are base classes provided for [Readable][] streams, [Writable][]\nstreams, [Duplex][] streams, and [Transform][] streams.\n\n

\n

This document is split up into 3 sections. The first explains the\nparts of the API that you need to be aware of to use streams in your\nprograms. If you never implement a streaming API yourself, you can\nstop there.\n\n

\n

The second section explains the parts of the API that you need to use\nif you implement your own custom streams yourself. The API is\ndesigned to make this easy for you to do.\n\n

\n

The third section goes into more depth about how streams work,\nincluding some of the internal mechanisms and functions that you\nshould probably not modify unless you definitely know what you are\ndoing.\n\n\n

\n", "classes": [ { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

The Readable stream interface is the abstraction for a source of\ndata that you are reading from. In other words, data comes out of a\nReadable stream.\n\n

\n

A Readable stream will not start emitting data until you indicate that\nyou are ready to receive it.\n\n

\n

Readable streams have two "modes": a flowing mode and a non-flowing\nmode. When in flowing mode, data is read from the underlying system\nand provided to your program as fast as possible. In non-flowing\nmode, you must explicitly call stream.read() to get chunks of data\nout.\n\n

\n

Examples of readable streams include:\n\n

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

When a chunk of data can be read from the stream, it will emit a\n'readable' event.\n\n

\n

In some cases, listening for a 'readable' event will cause some data\nto be read into the internal buffer from the underlying system, if it\nhadn't already.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // there is some data to read now\n})
\n

Once the internal buffer is drained, a readable event will fire\nagain when more data is available.\n\n

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

If you attach a data event listener, then it will switch the stream\ninto flowing mode, and data will be passed to your handler as soon as\nit is available.\n\n

\n

If you just want to get all the data out of the stream as fast as\npossible, this is the best way to do so.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})
\n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

This event fires when there will be no more data to read.\n\n

\n

Note that the end event will not fire unless the data is\ncompletely consumed. This can be done by switching into flowing mode,\nor by calling read() repeatedly until you get to the end.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})\nreadable.on('end', function() {\n  console.log('there will be no more data.');\n});
\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n

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

Emitted if there was an error receiving data.\n\n

\n" } ], "methods": [ { "textRaw": "readable.read([size])", "type": "method", "name": "read", "signatures": [ { "return": { "textRaw": "Return {String | Buffer | null} ", "name": "return", "type": "String | Buffer | null" }, "params": [ { "textRaw": "`size` {Number} Optional argument to specify how much data to read. ", "name": "size", "type": "Number", "desc": "Optional argument to specify how much data to read.", "optional": true } ] }, { "params": [ { "name": "size", "optional": true } ] } ], "desc": "

The read() method pulls some data out of the internal buffer and\nreturns it. If there is no data available, then it will return\nnull.\n\n

\n

If you pass in a size argument, then it will return that many\nbytes. If size bytes are not available, then it will return null.\n\n

\n

If you do not specify a size argument, then it will return all the\ndata in the internal buffer.\n\n

\n

This method should only be called in non-flowing mode. In\nflowing-mode, this method is called automatically until the internal\nbuffer is drained.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  var chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log('got %d bytes of data', chunk.length);\n  }\n});
\n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The encoding to use. ", "name": "encoding", "type": "String", "desc": "The encoding to use." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

Call this function to cause the stream to return strings of the\nspecified encoding instead of Buffer objects. For example, if you do\nreadable.setEncoding('utf8'), then the output data will be\ninterpreted as UTF-8 data, and returned as strings. If you do\nreadable.setEncoding('hex'), then the data will be encoded in\nhexadecimal string format.\n\n

\n

This properly handles multi-byte characters that would otherwise be\npotentially mangled if you simply pulled the Buffers directly and\ncalled buf.toString(encoding) on them. If you want to read the data\nas strings, always use this method.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', function(chunk) {\n  assert.equal(typeof chunk, 'string');\n  console.log('got %d characters of string data', chunk.length);\n})
\n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "desc": "

This method will cause the readable stream to resume emitting data\nevents.\n\n

\n

This method will switch the stream into flowing-mode. If you do not\nwant to consume the data from a stream, but you do want to get to\nits end event, you can call readable.resume() to open the flow of\ndata.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.resume();\nreadable.on('end', function(chunk) {\n  console.log('got to the end, but did not read anything');\n})
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "desc": "

This method will cause a stream in flowing-mode to stop emitting\ndata events. Any data that becomes available will remain in the\ninternal buffer.\n\n

\n

This method is only relevant in flowing mode. When called on a\nnon-flowing stream, it will switch into flowing mode, but remain\npaused.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n  readable.pause();\n  console.log('there will be no more data for 1 second');\n  setTimeout(function() {\n    console.log('now data will start flowing again');\n    readable.resume();\n  }, 1000);\n})
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pipe(destination, [options])", "type": "method", "name": "pipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} The destination for writing data ", "name": "destination", "type": "[Writable][] Stream", "desc": "The destination for writing data" }, { "textRaw": "`options` {Object} Pipe options ", "options": [ { "textRaw": "`end` {Boolean} End the writer when the reader ends. Default = `true` ", "name": "end", "type": "Boolean", "desc": "End the writer when the reader ends. Default = `true`" } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "desc": "

This method pulls all the data out of a readable stream, and writes it\nto the supplied destination, automatically managing the flow so that\nthe destination is not overwhelmed by a fast readable stream.\n\n

\n

Multiple destinations can be piped to safely.\n\n

\n
var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);
\n

This function returns the destination stream, so you can set up pipe\nchains like so:\n\n

\n
var r = fs.createReadStream('file.txt');\nvar z = zlib.createGzip();\nvar w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);
\n

For example, emulating the Unix cat command:\n\n

\n
process.stdin.pipe(process.stdout);
\n

By default [end()][] is called on the destination when the source stream\nemits end, so that destination is no longer writable. Pass { end:\nfalse } as options to keep the destination stream open.\n\n

\n

This keeps writer open so that "Goodbye" can be written at the\nend.\n\n

\n
reader.pipe(writer, { end: false });\nreader.on('end', function() {\n  writer.end('Goodbye\\n');\n});
\n

Note that process.stderr and process.stdout are never closed until\nthe process exits, regardless of the specified options.\n\n

\n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} Optional specific stream to unpipe ", "name": "destination", "type": "[Writable][] Stream", "desc": "Optional specific stream to unpipe", "optional": true } ] }, { "params": [ { "name": "destination", "optional": true } ] } ], "desc": "

This method will remove the hooks set up for a previous pipe() call.\n\n

\n

If the destination is not specified, then all pipes are removed.\n\n

\n

If the destination is specified, but no pipe is set up for it, then\nthis is a no-op.\n\n

\n
var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(function() {\n  console.log('stop writing to file.txt');\n  readable.unpipe(writable);\n  console.log('manually close the file stream');\n  writable.end();\n}, 1000);
\n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} Chunk of data to unshift onto the read queue ", "name": "chunk", "type": "Buffer | String", "desc": "Chunk of data to unshift onto the read queue" } ] }, { "params": [ { "name": "chunk" } ] } ], "desc": "

This is useful in certain cases where a stream is being consumed by a\nparser, which needs to "un-consume" some data that it has\noptimistically pulled out of the source, so that the stream can be\npassed on to some other party.\n\n

\n

If you find that you must often call stream.unshift(chunk) in your\nprograms, consider implementing a [Transform][] stream instead. (See API\nfor Stream Implementors, below.)\n\n

\n
// Pull off a header delimited by \\n\\n\n// use unshift() if we get too much\n// Call the callback with (error, header, stream)\nvar StringDecoder = require('string_decoder').StringDecoder;\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  var decoder = new StringDecoder('utf8');\n  var header = '';\n  function onReadable() {\n    var chunk;\n    while (null !== (chunk = stream.read())) {\n      var str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        var split = str.split(/\\n\\n/);\n        header += split.shift();\n        var remaining = split.join('\\n\\n');\n        var buf = new Buffer(remaining, 'utf8');\n        if (buf.length)\n          stream.unshift(buf);\n        stream.removeListener('error', callback);\n        stream.removeListener('readable', onReadable);\n        // now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // still reading the header.\n        header += str;\n      }\n    }\n  }\n}
\n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream ", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] }, { "params": [ { "name": "stream" } ] } ], "desc": "

Versions of Node prior to v0.10 had streams that did not implement the\nentire Streams API as it is today. (See "Compatibility" below for\nmore information.)\n\n

\n

If you are using an older Node library that emits 'data' events and\nhas a pause() method that is advisory only, then you can use the\nwrap() method to create a [Readable][] stream that uses the old stream\nas its data source.\n\n

\n

You will very rarely ever need to call this function, but it exists\nas a convenience for interacting with old Node programs and libraries.\n\n

\n

For example:\n\n

\n
var OldReader = require('./old-api-module.js').OldReader;\nvar oreader = new OldReader;\nvar Readable = require('stream').Readable;\nvar myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', function() {\n  myReader.read(); // etc.\n});
\n" } ] }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

The Writable stream interface is an abstraction for a destination\nthat you are writing data to.\n\n

\n

Examples of writable streams include:\n\n

\n\n", "methods": [ { "textRaw": "writable.write(chunk, [encoding], [callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns: {Boolean} True if the data was handled completely. ", "name": "return", "type": "Boolean", "desc": "True if the data was handled completely." }, "params": [ { "textRaw": "`chunk` {String | Buffer} The data to write ", "name": "chunk", "type": "String | Buffer", "desc": "The data to write" }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed ", "name": "callback", "type": "Function", "desc": "Callback for when this chunk of data is flushed", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

This method writes some data to the underlying system, and calls the\nsupplied callback once the data has been fully handled.\n\n

\n

The return value indicates if you should continue writing right now.\nIf the data had to be buffered internally, then it will return\nfalse. Otherwise, it will return true.\n\n

\n

This return value is strictly advisory. You MAY continue to write,\neven if it returns false. However, writes will be buffered in\nmemory, so it is best not to do this excessively. Instead, wait for\nthe drain event before writing more data.\n\n

\n" }, { "textRaw": "writable.end([chunk], [encoding], [callback])", "type": "method", "name": "end", "signatures": [ { "params": [ { "textRaw": "`chunk` {String | Buffer} Optional data to write ", "name": "chunk", "type": "String | Buffer", "desc": "Optional data to write", "optional": true }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the stream is finished ", "name": "callback", "type": "Function", "desc": "Optional callback for when the stream is finished", "optional": true } ] }, { "params": [ { "name": "chunk", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Call this method when no more data will be written to the stream. If\nsupplied, the callback is attached as a listener on the finish event.\n\n

\n

Calling [write()][] after calling [end()][] will raise an error.\n\n

\n
// write 'hello, ' and then end with 'world!'\nvar file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// writing more now is not allowed!
\n" } ], "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

If a [writable.write(chunk)][] call returns false, then the drain\nevent will indicate when it is appropriate to begin writing more data\nto the stream.\n\n

\n
// Write the data to the supplied writable stream 1MM times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  var i = 1000000;\n  write();\n  function write() {\n    var ok = true;\n    do {\n      i -= 1;\n      if (i === 0) {\n        // last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // see if we should continue, or wait\n        // don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // had to stop early!\n      // write some more once it drains\n      writer.once('drain', write);\n    }\n  }\n}
\n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

When the [end()][] method has been called, and all data has been flushed\nto the underlying system, this event is emitted.\n\n

\n
var writer = getWritableStreamSomehow();\nfor (var i = 0; i < 100; i ++) {\n  writer.write('hello, #' + i + '!\\n');\n}\nwriter.end('this is the end\\n');\nwriter.on('finish', function() {\n  console.error('all writes are now complete.');\n});
\n", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "params": [], "desc": "

This is emitted whenever the pipe() method is called on a readable\nstream, adding this writable to its set of destinations.\n\n

\n
var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('pipe', function(src) {\n  console.error('something is piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);
\n" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "

This is emitted whenever the [unpipe()][] method is called on a\nreadable stream, removing this writable from its set of destinations.\n\n

\n
var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('unpipe', function(src) {\n  console.error('something has stopped piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);
\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted if there was an error when writing or piping data.\n\n

\n" } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

Duplex streams are streams that implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

\n

Examples of Duplex streams include:\n\n

\n\n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

Transform streams are [Duplex][] streams where the output is in some way\ncomputed from the input. They implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

\n

Examples of Transform streams include:\n\n

\n\n" } ], "miscs": [ { "textRaw": "API for Stream Consumers", "name": "API for Stream Consumers", "type": "misc", "desc": "

Streams can be either [Readable][], [Writable][], or both ([Duplex][]).\n\n

\n

All streams are EventEmitters, but they also have other custom methods\nand properties depending on whether they are Readable, Writable, or\nDuplex.\n\n

\n

If a stream is both Readable and Writable, then it implements all of\nthe methods and events below. So, a [Duplex][] or [Transform][] stream is\nfully described by this API, though their implementation may be\nsomewhat different.\n\n

\n

It is not necessary to implement Stream interfaces in order to consume\nstreams in your programs. If you are implementing streaming\ninterfaces in your own program, please also refer to\n[API for Stream Implementors][] below.\n\n

\n

Almost all Node programs, no matter how simple, use Streams in some\nway. Here is an example of using Streams in a Node program:\n\n

\n
var http = require('http');\n\nvar server = http.createServer(function (req, res) {\n  // req is an http.IncomingMessage, which is a Readable Stream\n  // res is an http.ServerResponse, which is a Writable Stream\n\n  var body = '';\n  // we want to get the data as utf8 strings\n  // If you don't set an encoding, then you'll get Buffer objects\n  req.setEncoding('utf8');\n\n  // Readable streams emit 'data' events once a listener is added\n  req.on('data', function (chunk) {\n    body += chunk;\n  })\n\n  // the end event tells you that you have entire body\n  req.on('end', function () {\n    try {\n      var data = JSON.parse(body);\n    } catch (er) {\n      // uh oh!  bad json!\n      res.statusCode = 400;\n      return res.end('error: ' + er.message);\n    }\n\n    // write back something interesting to the user:\n    res.write(typeof data);\n    res.end();\n  })\n})\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d '{}'\n// object\n// $ curl localhost:1337 -d '"foo"'\n// string\n// $ curl localhost:1337 -d 'not json'\n// error: Unexpected token o
\n", "classes": [ { "textRaw": "Class: stream.Readable", "type": "class", "name": "stream.Readable", "desc": "

The Readable stream interface is the abstraction for a source of\ndata that you are reading from. In other words, data comes out of a\nReadable stream.\n\n

\n

A Readable stream will not start emitting data until you indicate that\nyou are ready to receive it.\n\n

\n

Readable streams have two "modes": a flowing mode and a non-flowing\nmode. When in flowing mode, data is read from the underlying system\nand provided to your program as fast as possible. In non-flowing\nmode, you must explicitly call stream.read() to get chunks of data\nout.\n\n

\n

Examples of readable streams include:\n\n

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

When a chunk of data can be read from the stream, it will emit a\n'readable' event.\n\n

\n

In some cases, listening for a 'readable' event will cause some data\nto be read into the internal buffer from the underlying system, if it\nhadn't already.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  // there is some data to read now\n})
\n

Once the internal buffer is drained, a readable event will fire\nagain when more data is available.\n\n

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

If you attach a data event listener, then it will switch the stream\ninto flowing mode, and data will be passed to your handler as soon as\nit is available.\n\n

\n

If you just want to get all the data out of the stream as fast as\npossible, this is the best way to do so.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})
\n" }, { "textRaw": "Event: 'end'", "type": "event", "name": "end", "desc": "

This event fires when there will be no more data to read.\n\n

\n

Note that the end event will not fire unless the data is\ncompletely consumed. This can be done by switching into flowing mode,\nor by calling read() repeatedly until you get to the end.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n})\nreadable.on('end', function() {\n  console.log('there will be no more data.');\n});
\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n

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

Emitted if there was an error receiving data.\n\n

\n" } ], "methods": [ { "textRaw": "readable.read([size])", "type": "method", "name": "read", "signatures": [ { "return": { "textRaw": "Return {String | Buffer | null} ", "name": "return", "type": "String | Buffer | null" }, "params": [ { "textRaw": "`size` {Number} Optional argument to specify how much data to read. ", "name": "size", "type": "Number", "desc": "Optional argument to specify how much data to read.", "optional": true } ] }, { "params": [ { "name": "size", "optional": true } ] } ], "desc": "

The read() method pulls some data out of the internal buffer and\nreturns it. If there is no data available, then it will return\nnull.\n\n

\n

If you pass in a size argument, then it will return that many\nbytes. If size bytes are not available, then it will return null.\n\n

\n

If you do not specify a size argument, then it will return all the\ndata in the internal buffer.\n\n

\n

This method should only be called in non-flowing mode. In\nflowing-mode, this method is called automatically until the internal\nbuffer is drained.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n  var chunk;\n  while (null !== (chunk = readable.read())) {\n    console.log('got %d bytes of data', chunk.length);\n  }\n});
\n" }, { "textRaw": "readable.setEncoding(encoding)", "type": "method", "name": "setEncoding", "signatures": [ { "params": [ { "textRaw": "`encoding` {String} The encoding to use. ", "name": "encoding", "type": "String", "desc": "The encoding to use." } ] }, { "params": [ { "name": "encoding" } ] } ], "desc": "

Call this function to cause the stream to return strings of the\nspecified encoding instead of Buffer objects. For example, if you do\nreadable.setEncoding('utf8'), then the output data will be\ninterpreted as UTF-8 data, and returned as strings. If you do\nreadable.setEncoding('hex'), then the data will be encoded in\nhexadecimal string format.\n\n

\n

This properly handles multi-byte characters that would otherwise be\npotentially mangled if you simply pulled the Buffers directly and\ncalled buf.toString(encoding) on them. If you want to read the data\nas strings, always use this method.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', function(chunk) {\n  assert.equal(typeof chunk, 'string');\n  console.log('got %d characters of string data', chunk.length);\n})
\n" }, { "textRaw": "readable.resume()", "type": "method", "name": "resume", "desc": "

This method will cause the readable stream to resume emitting data\nevents.\n\n

\n

This method will switch the stream into flowing-mode. If you do not\nwant to consume the data from a stream, but you do want to get to\nits end event, you can call readable.resume() to open the flow of\ndata.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.resume();\nreadable.on('end', function(chunk) {\n  console.log('got to the end, but did not read anything');\n})
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pause()", "type": "method", "name": "pause", "desc": "

This method will cause a stream in flowing-mode to stop emitting\ndata events. Any data that becomes available will remain in the\ninternal buffer.\n\n

\n

This method is only relevant in flowing mode. When called on a\nnon-flowing stream, it will switch into flowing mode, but remain\npaused.\n\n

\n
var readable = getReadableStreamSomehow();\nreadable.on('data', function(chunk) {\n  console.log('got %d bytes of data', chunk.length);\n  readable.pause();\n  console.log('there will be no more data for 1 second');\n  setTimeout(function() {\n    console.log('now data will start flowing again');\n    readable.resume();\n  }, 1000);\n})
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "readable.pipe(destination, [options])", "type": "method", "name": "pipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} The destination for writing data ", "name": "destination", "type": "[Writable][] Stream", "desc": "The destination for writing data" }, { "textRaw": "`options` {Object} Pipe options ", "options": [ { "textRaw": "`end` {Boolean} End the writer when the reader ends. Default = `true` ", "name": "end", "type": "Boolean", "desc": "End the writer when the reader ends. Default = `true`" } ], "name": "options", "type": "Object", "desc": "Pipe options", "optional": true } ] }, { "params": [ { "name": "destination" }, { "name": "options", "optional": true } ] } ], "desc": "

This method pulls all the data out of a readable stream, and writes it\nto the supplied destination, automatically managing the flow so that\nthe destination is not overwhelmed by a fast readable stream.\n\n

\n

Multiple destinations can be piped to safely.\n\n

\n
var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'\nreadable.pipe(writable);
\n

This function returns the destination stream, so you can set up pipe\nchains like so:\n\n

\n
var r = fs.createReadStream('file.txt');\nvar z = zlib.createGzip();\nvar w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);
\n

For example, emulating the Unix cat command:\n\n

\n
process.stdin.pipe(process.stdout);
\n

By default [end()][] is called on the destination when the source stream\nemits end, so that destination is no longer writable. Pass { end:\nfalse } as options to keep the destination stream open.\n\n

\n

This keeps writer open so that "Goodbye" can be written at the\nend.\n\n

\n
reader.pipe(writer, { end: false });\nreader.on('end', function() {\n  writer.end('Goodbye\\n');\n});
\n

Note that process.stderr and process.stdout are never closed until\nthe process exits, regardless of the specified options.\n\n

\n" }, { "textRaw": "readable.unpipe([destination])", "type": "method", "name": "unpipe", "signatures": [ { "params": [ { "textRaw": "`destination` {[Writable][] Stream} Optional specific stream to unpipe ", "name": "destination", "type": "[Writable][] Stream", "desc": "Optional specific stream to unpipe", "optional": true } ] }, { "params": [ { "name": "destination", "optional": true } ] } ], "desc": "

This method will remove the hooks set up for a previous pipe() call.\n\n

\n

If the destination is not specified, then all pipes are removed.\n\n

\n

If the destination is specified, but no pipe is set up for it, then\nthis is a no-op.\n\n

\n
var readable = getReadableStreamSomehow();\nvar writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second\nreadable.pipe(writable);\nsetTimeout(function() {\n  console.log('stop writing to file.txt');\n  readable.unpipe(writable);\n  console.log('manually close the file stream');\n  writable.end();\n}, 1000);
\n" }, { "textRaw": "readable.unshift(chunk)", "type": "method", "name": "unshift", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} Chunk of data to unshift onto the read queue ", "name": "chunk", "type": "Buffer | String", "desc": "Chunk of data to unshift onto the read queue" } ] }, { "params": [ { "name": "chunk" } ] } ], "desc": "

This is useful in certain cases where a stream is being consumed by a\nparser, which needs to "un-consume" some data that it has\noptimistically pulled out of the source, so that the stream can be\npassed on to some other party.\n\n

\n

If you find that you must often call stream.unshift(chunk) in your\nprograms, consider implementing a [Transform][] stream instead. (See API\nfor Stream Implementors, below.)\n\n

\n
// Pull off a header delimited by \\n\\n\n// use unshift() if we get too much\n// Call the callback with (error, header, stream)\nvar StringDecoder = require('string_decoder').StringDecoder;\nfunction parseHeader(stream, callback) {\n  stream.on('error', callback);\n  stream.on('readable', onReadable);\n  var decoder = new StringDecoder('utf8');\n  var header = '';\n  function onReadable() {\n    var chunk;\n    while (null !== (chunk = stream.read())) {\n      var str = decoder.write(chunk);\n      if (str.match(/\\n\\n/)) {\n        // found the header boundary\n        var split = str.split(/\\n\\n/);\n        header += split.shift();\n        var remaining = split.join('\\n\\n');\n        var buf = new Buffer(remaining, 'utf8');\n        if (buf.length)\n          stream.unshift(buf);\n        stream.removeListener('error', callback);\n        stream.removeListener('readable', onReadable);\n        // now the body of the message can be read from the stream.\n        callback(null, header, stream);\n      } else {\n        // still reading the header.\n        header += str;\n      }\n    }\n  }\n}
\n" }, { "textRaw": "readable.wrap(stream)", "type": "method", "name": "wrap", "signatures": [ { "params": [ { "textRaw": "`stream` {Stream} An \"old style\" readable stream ", "name": "stream", "type": "Stream", "desc": "An \"old style\" readable stream" } ] }, { "params": [ { "name": "stream" } ] } ], "desc": "

Versions of Node prior to v0.10 had streams that did not implement the\nentire Streams API as it is today. (See "Compatibility" below for\nmore information.)\n\n

\n

If you are using an older Node library that emits 'data' events and\nhas a pause() method that is advisory only, then you can use the\nwrap() method to create a [Readable][] stream that uses the old stream\nas its data source.\n\n

\n

You will very rarely ever need to call this function, but it exists\nas a convenience for interacting with old Node programs and libraries.\n\n

\n

For example:\n\n

\n
var OldReader = require('./old-api-module.js').OldReader;\nvar oreader = new OldReader;\nvar Readable = require('stream').Readable;\nvar myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', function() {\n  myReader.read(); // etc.\n});
\n" } ] }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

The Writable stream interface is an abstraction for a destination\nthat you are writing data to.\n\n

\n

Examples of writable streams include:\n\n

\n\n", "methods": [ { "textRaw": "writable.write(chunk, [encoding], [callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns: {Boolean} True if the data was handled completely. ", "name": "return", "type": "Boolean", "desc": "True if the data was handled completely." }, "params": [ { "textRaw": "`chunk` {String | Buffer} The data to write ", "name": "chunk", "type": "String | Buffer", "desc": "The data to write" }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Callback for when this chunk of data is flushed ", "name": "callback", "type": "Function", "desc": "Callback for when this chunk of data is flushed", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

This method writes some data to the underlying system, and calls the\nsupplied callback once the data has been fully handled.\n\n

\n

The return value indicates if you should continue writing right now.\nIf the data had to be buffered internally, then it will return\nfalse. Otherwise, it will return true.\n\n

\n

This return value is strictly advisory. You MAY continue to write,\neven if it returns false. However, writes will be buffered in\nmemory, so it is best not to do this excessively. Instead, wait for\nthe drain event before writing more data.\n\n

\n" }, { "textRaw": "writable.end([chunk], [encoding], [callback])", "type": "method", "name": "end", "signatures": [ { "params": [ { "textRaw": "`chunk` {String | Buffer} Optional data to write ", "name": "chunk", "type": "String | Buffer", "desc": "Optional data to write", "optional": true }, { "textRaw": "`encoding` {String} The encoding, if `chunk` is a String ", "name": "encoding", "type": "String", "desc": "The encoding, if `chunk` is a String", "optional": true }, { "textRaw": "`callback` {Function} Optional callback for when the stream is finished ", "name": "callback", "type": "Function", "desc": "Optional callback for when the stream is finished", "optional": true } ] }, { "params": [ { "name": "chunk", "optional": true }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

Call this method when no more data will be written to the stream. If\nsupplied, the callback is attached as a listener on the finish event.\n\n

\n

Calling [write()][] after calling [end()][] will raise an error.\n\n

\n
// write 'hello, ' and then end with 'world!'\nvar file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// writing more now is not allowed!
\n" } ], "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "

If a [writable.write(chunk)][] call returns false, then the drain\nevent will indicate when it is appropriate to begin writing more data\nto the stream.\n\n

\n
// Write the data to the supplied writable stream 1MM times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n  var i = 1000000;\n  write();\n  function write() {\n    var ok = true;\n    do {\n      i -= 1;\n      if (i === 0) {\n        // last time!\n        writer.write(data, encoding, callback);\n      } else {\n        // see if we should continue, or wait\n        // don't pass the callback, because we're not done yet.\n        ok = writer.write(data, encoding);\n      }\n    } while (i > 0 && ok);\n    if (i > 0) {\n      // had to stop early!\n      // write some more once it drains\n      writer.once('drain', write);\n    }\n  }\n}
\n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "

When the [end()][] method has been called, and all data has been flushed\nto the underlying system, this event is emitted.\n\n

\n
var writer = getWritableStreamSomehow();\nfor (var i = 0; i < 100; i ++) {\n  writer.write('hello, #' + i + '!\\n');\n}\nwriter.end('this is the end\\n');\nwriter.on('finish', function() {\n  console.error('all writes are now complete.');\n});
\n", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "params": [], "desc": "

This is emitted whenever the pipe() method is called on a readable\nstream, adding this writable to its set of destinations.\n\n

\n
var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('pipe', function(src) {\n  console.error('something is piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);
\n" }, { "textRaw": "Event: 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "

This is emitted whenever the [unpipe()][] method is called on a\nreadable stream, removing this writable from its set of destinations.\n\n

\n
var writer = getWritableStreamSomehow();\nvar reader = getReadableStreamSomehow();\nwriter.on('unpipe', function(src) {\n  console.error('something has stopped piping into the writer');\n  assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);
\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "

Emitted if there was an error when writing or piping data.\n\n

\n" } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

Duplex streams are streams that implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

\n

Examples of Duplex streams include:\n\n

\n\n" }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

Transform streams are [Duplex][] streams where the output is in some way\ncomputed from the input. They implement both the [Readable][] and\n[Writable][] interfaces. See above for usage.\n\n

\n

Examples of Transform streams include:\n\n

\n\n" } ] }, { "textRaw": "API for Stream Implementors", "name": "API for Stream Implementors", "type": "misc", "desc": "

To implement any sort of stream, the pattern is the same:\n\n

\n
    \n
  1. Extend the appropriate parent class in your own subclass. (The\n[util.inherits][] method is particularly helpful for this.)
  2. \n
  3. Call the appropriate parent class constructor in your constructor,\nto be sure that the internal mechanisms are set up properly.
  4. \n
  5. Implement one or more specific methods, as detailed below.
  6. \n
\n

The class to extend and the method(s) to implement depend on the sort\nof stream class you are writing:\n\n

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
\n

Use-case

\n
\n

Class

\n
\n

Method(s) to implement

\n
\n

Reading only

\n
\n

Readable

\n
\n

[_read][]

\n
\n

Writing only

\n
\n

Writable

\n
\n

[_write][]

\n
\n

Reading and writing

\n
\n

Duplex

\n
\n

[_read][], [_write][]

\n
\n

Operate on written data, then read the result

\n
\n

Transform

\n
\n

_transform, _flush

\n
\n\n

In your implementation code, it is very important to never call the\nmethods described in [API for Stream Consumers][] above. Otherwise, you\ncan potentially cause adverse side effects in programs that consume\nyour streaming interfaces.\n\n

\n", "examples": [ { "textRaw": "Class: stream.Readable", "type": "example", "name": "stream.Readable", "desc": "

stream.Readable is an abstract class designed to be extended with an\nunderlying implementation of the [_read(size)][] method.\n\n

\n

Please see above under [API for Stream Consumers][] for how to consume\nstreams in your programs. What follows is an explanation of how to\nimplement Readable streams in your programs.\n\n

\n

Example: A Counting Stream

\n

This is a basic example of a Readable stream. It emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.\n\n

\n
var Readable = require('stream').Readable;\nvar util = require('util');\nutil.inherits(Counter, Readable);\n\nfunction Counter(opt) {\n  Readable.call(this, opt);\n  this._max = 1000000;\n  this._index = 1;\n}\n\nCounter.prototype._read = function() {\n  var i = this._index++;\n  if (i > this._max)\n    this.push(null);\n  else {\n    var str = '' + i;\n    var buf = new Buffer(str, 'ascii');\n    this.push(buf);\n  }\n};
\n

Example: SimpleProtocol v1 (Sub-optimal)

\n

This is similar to the parseHeader function described above, but\nimplemented as a custom stream. Also, note that this implementation\ndoes not convert the incoming data to a string.\n\n

\n

However, this would be better implemented as a [Transform][] stream. See\nbelow for a better implementation.\n\n

\n
// A parser for a simple data protocol.\n// The "header" is a JSON object, followed by 2 \\n characters, and\n// then a message body.\n//\n// NOTE: This can be done more simply as a Transform stream!\n// Using Readable directly for this is sub-optimal.  See the\n// alternative example below under the Transform section.\n\nvar Readable = require('stream').Readable;\nvar util = require('util');\n\nutil.inherits(SimpleProtocol, Readable);\n\nfunction SimpleProtocol(source, options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(source, options);\n\n  Readable.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n\n  // source is a readable stream, such as a socket or file\n  this._source = source;\n\n  var self = this;\n  source.on('end', function() {\n    self.push(null);\n  });\n\n  // give it a kick whenever the source is readable\n  // read(0) will not consume any bytes\n  source.on('readable', function() {\n    self.read(0);\n  });\n\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._read = function(n) {\n  if (!this._inBody) {\n    var chunk = this._source.read();\n\n    // if the source doesn't have data, we don't have data yet.\n    if (chunk === null)\n      return this.push('');\n\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n      this.push('');\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // now, because we got some extra data, unshift the rest\n      // back into the read queue so that our consumer will see it.\n      var b = chunk.slice(split);\n      this.unshift(b);\n\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n    }\n  } else {\n    // from there on, just provide the data to our consumer.\n    // careful not to push(null), since that would indicate EOF.\n    var chunk = this._source.read();\n    if (chunk) this.push(chunk);\n  }\n};\n\n// Usage:\n// var parser = new SimpleProtocol(source);\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
\n", "methods": [ { "textRaw": "new stream.Readable([options])", "type": "method", "name": "Readable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb" }, { "textRaw": "`encoding` {String} If specified, then buffers will be decoded to strings using the specified encoding. Default=null ", "name": "encoding", "type": "String", "desc": "If specified, then buffers will be decoded to strings using the specified encoding. Default=null" }, { "textRaw": "`objectMode` {Boolean} Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false ", "name": "objectMode", "type": "Boolean", "desc": "Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

In classes that extend the Readable class, make sure to call the\nReadable constructor so that the buffering settings can be properly\ninitialized.\n\n

\n" }, { "textRaw": "readable.\\_read(size)", "type": "method", "name": "\\_read", "signatures": [ { "params": [ { "textRaw": "`size` {Number} Number of bytes to read asynchronously ", "name": "size", "type": "Number", "desc": "Number of bytes to read asynchronously" } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

Note: Implement this function, but do NOT call it directly.\n\n

\n

This function should NOT be called directly. It should be implemented\nby child classes, and only called by the internal Readable class\nmethods.\n\n

\n

All Readable stream implementations must provide a _read method to\nfetch data from the underlying resource.\n\n

\n

This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

\n

When data is available, put it into the read queue by calling\nreadable.push(chunk). If push returns false, then you should stop\nreading. When _read is called again, you should start pushing more\ndata.\n\n

\n

The size argument is advisory. Implementations where a "read" is a\nsingle call that returns data can use this to know how much data to\nfetch. Implementations where that is not relevant, such as TCP or\nTLS, may ignore this argument, and simply provide data whenever it\nbecomes available. There is no need, for example to "wait" until\nsize bytes are available before calling [stream.push(chunk)][].\n\n

\n" }, { "textRaw": "readable.push(chunk, [encoding])", "type": "method", "name": "push", "signatures": [ { "return": { "textRaw": "return {Boolean} Whether or not more pushes should be performed ", "name": "return", "type": "Boolean", "desc": "Whether or not more pushes should be performed" }, "params": [ { "textRaw": "`chunk` {Buffer | null | String} Chunk of data to push into the read queue ", "name": "chunk", "type": "Buffer | null | String", "desc": "Chunk of data to push into the read queue" }, { "textRaw": "`encoding` {String} Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'` ", "name": "encoding", "type": "String", "desc": "Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'`", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ], "desc": "

Note: This function should be called by Readable implementors, NOT\nby consumers of Readable streams.\n\n

\n

The _read() function will not be called again until at least one\npush(chunk) call is made.\n\n

\n

The Readable class works by putting data into a read queue to be\npulled out later by calling the read() method when the 'readable'\nevent fires.\n\n

\n

The push() method will explicitly insert some data into the read\nqueue. If it is called with null then it will signal the end of the\ndata (EOF).\n\n

\n

This API is designed to be as flexible as possible. For example,\nyou may be wrapping a lower-level source which has some sort of\npause/resume mechanism, and a data callback. In those cases, you\ncould wrap the low-level source object by doing something like this:\n\n

\n
// source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nutil.inherits(SourceWrapper, Readable);\n\nfunction SourceWrapper(options) {\n  Readable.call(this, options);\n\n  this._source = getLowlevelSourceObject();\n  var self = this;\n\n  // Every time there's data, we push it into the internal buffer.\n  this._source.ondata = function(chunk) {\n    // if push() returns false, then we need to stop reading from source\n    if (!self.push(chunk))\n      self._source.readStop();\n  };\n\n  // When the source ends, we push the EOF-signalling `null` chunk\n  this._source.onend = function() {\n    self.push(null);\n  };\n}\n\n// _read will be called when the stream wants to pull more data in\n// the advisory size argument is ignored in this case.\nSourceWrapper.prototype._read = function(size) {\n  this._source.readStart();\n};
\n" } ] } ], "classes": [ { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "

stream.Writable is an abstract class designed to be extended with an\nunderlying implementation of the [_write(chunk, encoding, callback)][] method.\n\n

\n

Please see above under [API for Stream Consumers][] for how to consume\nwritable streams in your programs. What follows is an explanation of\nhow to implement Writable streams in your programs.\n\n

\n", "methods": [ { "textRaw": "new stream.Writable([options])", "type": "method", "name": "Writable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} Buffer level when [`write()`][] starts returning false. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "Buffer level when [`write()`][] starts returning false. Default=16kb" }, { "textRaw": "`decodeStrings` {Boolean} Whether or not to decode strings into Buffers before passing them to [`_write()`][]. Default=true ", "name": "decodeStrings", "type": "Boolean", "desc": "Whether or not to decode strings into Buffers before passing them to [`_write()`][]. Default=true" }, { "textRaw": "`objectMode` {Boolean} Whether or not the `write(anyObj)` is a valid operation. If set you can write arbitrary data instead of only `Buffer` / `String` data. Default=false ", "name": "objectMode", "type": "Boolean", "desc": "Whether or not the `write(anyObj)` is a valid operation. If set you can write arbitrary data instead of only `Buffer` / `String` data. Default=false" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

In classes that extend the Writable class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n

\n" }, { "textRaw": "writable.\\_write(chunk, encoding, callback)", "type": "method", "name": "\\_write", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} The chunk to be written. Will always be a buffer unless the `decodeStrings` option was set to `false`. ", "name": "chunk", "type": "Buffer | String", "desc": "The chunk to be written. Will always be a buffer unless the `decodeStrings` option was set to `false`." }, { "textRaw": "`encoding` {String} If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will **always** be a buffer unless the `decodeStrings` option is explicitly set to `false`. ", "name": "encoding", "type": "String", "desc": "If the chunk is a string, then this is the encoding type. Ignore chunk is a buffer. Note that chunk will **always** be a buffer unless the `decodeStrings` option is explicitly set to `false`." }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

All Writable stream implementations must provide a [_write()][]\nmethod to send data to the underlying resource.\n\n

\n

Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Writable\nclass methods only.\n\n

\n

Call the callback using the standard callback(error) pattern to\nsignal that the write completed successfully or with an error.\n\n

\n

If the decodeStrings flag is set in the constructor options, then\nchunk may be a string rather than a Buffer, and encoding will\nindicate the sort of string that it is. This is to support\nimplementations that have an optimized handling for certain string\ndata encodings. If you do not explicitly set the decodeStrings\noption to false, then you can safely ignore the encoding argument,\nand assume that chunk will always be a Buffer.\n\n

\n

This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n\n

\n" } ] }, { "textRaw": "Class: stream.Duplex", "type": "class", "name": "stream.Duplex", "desc": "

A "duplex" stream is one that is both Readable and Writable, such as a\nTCP socket connection.\n\n

\n

Note that stream.Duplex is an abstract class designed to be extended\nwith an underlying implementation of the _read(size) and\n[_write(chunk, encoding, callback)][] methods as you would with a\nReadable or Writable stream class.\n\n

\n

Since JavaScript doesn't have multiple prototypal inheritance, this\nclass prototypally inherits from Readable, and then parasitically from\nWritable. It is thus up to the user to implement both the lowlevel\n_read(n) method as well as the lowlevel\n[_write(chunk, encoding, callback)][] method on extension duplex classes.\n\n

\n", "methods": [ { "textRaw": "new stream.Duplex(options)", "type": "method", "name": "Duplex", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both Writable and Readable constructors. Also has the following fields: ", "options": [ { "textRaw": "`allowHalfOpen` {Boolean} Default=true. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa. ", "name": "allowHalfOpen", "type": "Boolean", "desc": "Default=true. If set to `false`, then the stream will automatically end the readable side when the writable side ends and vice versa." } ], "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors. Also has the following fields:" } ] }, { "params": [ { "name": "options" } ] } ], "desc": "

In classes that extend the Duplex class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n\n

\n" } ] }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "

A "transform" stream is a duplex stream where the output is causally\nconnected in some way to the input, such as a [zlib][] stream or a\n[crypto][] stream.\n\n

\n

There is no requirement that the output be the same size as the input,\nthe same number of chunks, or arrive at the same time. For example, a\nHash stream will only ever have a single chunk of output which is\nprovided when the input is ended. A zlib stream will produce output\nthat is either much smaller or much larger than its input.\n\n

\n

Rather than implement the [_read()][] and [_write()][] methods, Transform\nclasses must implement the _transform() method, and may optionally\nalso implement the _flush() method. (See below.)\n\n

\n", "methods": [ { "textRaw": "new stream.Transform([options])", "type": "method", "name": "Transform", "signatures": [ { "params": [ { "textRaw": "`options` {Object} Passed to both Writable and Readable constructors. ", "name": "options", "type": "Object", "desc": "Passed to both Writable and Readable constructors.", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

In classes that extend the Transform class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n

\n" }, { "textRaw": "transform.\\_transform(chunk, encoding, callback)", "type": "method", "name": "\\_transform", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | String} The chunk to be transformed. Will always be a buffer unless the `decodeStrings` option was set to `false`. ", "name": "chunk", "type": "Buffer | String", "desc": "The chunk to be transformed. Will always be a buffer unless the `decodeStrings` option was set to `false`." }, { "textRaw": "`encoding` {String} If the chunk is a string, then this is the encoding type. (Ignore if `decodeStrings` chunk is a buffer.) ", "name": "encoding", "type": "String", "desc": "If the chunk is a string, then this is the encoding type. (Ignore if `decodeStrings` chunk is a buffer.)" }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument and data) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument and data) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding" }, { "name": "callback" } ] } ], "desc": "

Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Transform\nclass methods only.\n\n

\n

All Transform stream implementations must provide a _transform\nmethod to accept input and produce output.\n\n

\n

_transform should do whatever has to be done in this specific\nTransform class, to handle the bytes being written, and pass them off\nto the readable portion of the interface. Do asynchronous I/O,\nprocess things, and so on.\n\n

\n

Call transform.push(outputChunk) 0 or more times to generate output\nfrom this input chunk, depending on how much data you want to output\nas a result of this chunk.\n\n

\n

Call the callback function only when the current chunk is completely\nconsumed. Note that there may or may not be output as a result of any\nparticular input chunk. If you supply as the second argument to the\nit will be passed to push method, in other words the following are\nequivalent:\n\n

\n
transform.prototype._transform = function (data, encoding, callback) {\n  this.push(data);\n  callback();\n}\n\ntransform.prototype._transform = function (data, encoding, callback) {\n  callback(null, data);\n}
\n

This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

\n" }, { "textRaw": "transform.\\_flush(callback)", "type": "method", "name": "\\_flush", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done flushing any remaining data. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done flushing any remaining data." } ] }, { "params": [ { "name": "callback" } ] } ], "desc": "

Note: This function MUST NOT be called directly. It MAY be implemented\nby child classes, and if so, will be called by the internal Transform\nclass methods only.\n\n

\n

In some cases, your transform operation may need to emit a bit more\ndata at the end of the stream. For example, a Zlib compression\nstream will store up some internal state so that it can optimally\ncompress the output. At the end, however, it needs to do the best it\ncan with what is left, so that the data will be complete.\n\n

\n

In those cases, you can implement a _flush method, which will be\ncalled at the very end, after all the written data is consumed, but\nbefore emitting end to signal the end of the readable side. Just\nlike with _transform, call transform.push(chunk) zero or more\ntimes, as appropriate, and call callback when the flush operation is\ncomplete.\n\n

\n

This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

\n" } ], "modules": [ { "textRaw": "Events: 'finish' and 'end'", "name": "events:_'finish'_and_'end'", "desc": "

The [finish][] and [end][] events are from the parent Writable\nand Readable classes respectively. The finish event is fired after\n.end() is called and all chunks have been processed by _transform,\nend is fired after all data has been output which is after the callback\nin _flush has been called.\n\n

\n

Example: SimpleProtocol parser v2

\n

The example above of a simple protocol parser can be implemented\nsimply by using the higher level [Transform][] stream class, similar to\nthe parseHeader and SimpleProtocol v1 examples above.\n\n

\n

In this example, rather than providing the input as an argument, it\nwould be piped into the parser, which is a more idiomatic Node stream\napproach.\n\n

\n
var util = require('util');\nvar Transform = require('stream').Transform;\nutil.inherits(SimpleProtocol, Transform);\n\nfunction SimpleProtocol(options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(options);\n\n  Transform.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._transform = function(chunk, encoding, done) {\n  if (!this._inBody) {\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n\n      // now, because we got some extra data, emit this first.\n      this.push(chunk.slice(split));\n    }\n  } else {\n    // from there on, just provide the data to our consumer as-is.\n    this.push(chunk);\n  }\n  done();\n};\n\n// Usage:\n// var parser = new SimpleProtocol();\n// source.pipe(parser)\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
\n", "type": "module", "displayName": "Events: 'finish' and 'end'" } ] }, { "textRaw": "Class: stream.PassThrough", "type": "class", "name": "stream.PassThrough", "desc": "

This is a trivial implementation of a [Transform][] stream that simply\npasses the input bytes across to the output. Its purpose is mainly\nfor examples and testing, but there are occasionally use cases where\nit can come in handy as a building block for novel sorts of streams.\n\n\n

\n" } ] }, { "textRaw": "Streams: Under the Hood", "name": "Streams: Under the Hood", "type": "misc", "miscs": [ { "textRaw": "Buffering", "name": "Buffering", "type": "misc", "desc": "

Both Writable and Readable streams will buffer data on an internal\nobject called _writableState.buffer or _readableState.buffer,\nrespectively.\n\n

\n

The amount of data that will potentially be buffered depends on the\nhighWaterMark option which is passed into the constructor.\n\n

\n

Buffering in Readable streams happens when the implementation calls\n[stream.push(chunk)][]. If the consumer of the Stream does not call\nstream.read(), then the data will sit in the internal queue until it\nis consumed.\n\n

\n

Buffering in Writable streams happens when the user calls\n[stream.write(chunk)][] repeatedly, even when write() returns false.\n\n

\n

The purpose of streams, especially with the pipe() method, is to\nlimit the buffering of data to acceptable levels, so that sources and\ndestinations of varying speed will not overwhelm the available memory.\n\n

\n" }, { "textRaw": "`stream.read(0)`", "name": "`stream.read(0)`", "desc": "

There are some cases where you want to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In that case, you can call stream.read(0), which will always\nreturn null.\n\n

\n

If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling read(0) will trigger\na low-level _read call.\n\n

\n

There is almost never a need to do this. However, you will see some\ncases in Node's internals where this is done, particularly in the\nReadable stream class internals.\n\n

\n", "type": "misc", "displayName": "`stream.read(0)`" }, { "textRaw": "`stream.push('')`", "name": "`stream.push('')`", "desc": "

Pushing a zero-byte string or Buffer (when not in [Object mode][]) has an\ninteresting side effect. Because it is a call to\n[stream.push()][], it will end the reading process. However, it\ndoes not add any data to the readable buffer, so there's nothing for\na user to consume.\n\n

\n

Very rarely, there are cases where you have no data to provide now,\nbut the consumer of your stream (or, perhaps, another bit of your own\ncode) will know when to check again, by calling stream.read(0). In\nthose cases, you may call stream.push('').\n\n

\n

So far, the only use case for this functionality is in the\n[tls.CryptoStream][] class, which is deprecated in Node v0.12. If you\nfind that you have to use stream.push(''), please consider another\napproach, because it almost certainly indicates that something is\nhorribly wrong.\n\n

\n", "type": "misc", "displayName": "`stream.push('')`" }, { "textRaw": "Compatibility with Older Node Versions", "name": "Compatibility with Older Node Versions", "type": "misc", "desc": "

In versions of Node prior to v0.10, the Readable stream interface was\nsimpler, but also less powerful and less useful.\n\n

\n\n

In Node v0.10, the Readable class described below was added. For\nbackwards compatibility with older Node programs, Readable streams\nswitch into "flowing mode" when a 'data' event handler is added, or\nwhen the pause() or resume() methods are called. The effect is\nthat, even if you are not using the new read() method and\n'readable' event, you no longer have to worry about losing 'data'\nchunks.\n\n

\n

Most programs will continue to function normally. However, this\nintroduces an edge case in the following conditions:\n\n

\n\n

For example, consider the following code:\n\n

\n
// WARNING!  BROKEN!\nnet.createServer(function(socket) {\n\n  // we add an 'end' method, but never consume the data\n  socket.on('end', function() {\n    // It will never get here.\n    socket.end('I got your message (but didnt read it)\\n');\n  });\n\n}).listen(1337);
\n

In versions of node prior to v0.10, the incoming message data would be\nsimply discarded. However, in Node v0.10 and beyond, the socket will\nremain paused forever.\n\n

\n

The workaround in this situation is to call the resume() method to\ntrigger "old mode" behavior:\n\n

\n
// Workaround\nnet.createServer(function(socket) {\n\n  socket.on('end', function() {\n    socket.end('I got your message (but didnt read it)\\n');\n  });\n\n  // start the flow of data, discarding it.\n  socket.resume();\n\n}).listen(1337);
\n

In addition to new Readable streams switching into flowing-mode, pre-v0.10\nstyle streams can be wrapped in a Readable class using the wrap()\nmethod.\n\n\n

\n" }, { "textRaw": "Object Mode", "name": "Object Mode", "type": "misc", "desc": "

Normally, Streams operate on Strings and Buffers exclusively.\n\n

\n

Streams that are in object mode can emit generic JavaScript values\nother than Buffers and Strings.\n\n

\n

A Readable stream in object mode will always return a single item from\na call to stream.read(size), regardless of what the size argument\nis.\n\n

\n

A Writable stream in object mode will always ignore the encoding\nargument to stream.write(data, encoding).\n\n

\n

The special value null still retains its special value for object\nmode streams. That is, for object mode readable streams, null as a\nreturn value from stream.read() indicates that there is no more\ndata, and [stream.push(null)][] will signal the end of stream data\n(EOF).\n\n

\n

No streams in Node core are object mode streams. This pattern is only\nused by userland streaming libraries.\n\n

\n

You should set objectMode in your stream child class constructor on\nthe options object. Setting objectMode mid-stream is not safe.\n\n

\n" }, { "textRaw": "State Objects", "name": "state_objects", "desc": "

[Readable][] streams have a member object called _readableState.\n[Writable][] streams have a member object called _writableState.\n[Duplex][] streams have both.\n\n

\n

These objects should generally not be modified in child classes.\nHowever, if you have a Duplex or Transform stream that should be in\nobjectMode on the readable side, and not in objectMode on the\nwritable side, then you may do this in the constructor by setting the\nflag explicitly on the appropriate state object.\n\n

\n
var util = require('util');\nvar StringDecoder = require('string_decoder').StringDecoder;\nvar Transform = require('stream').Transform;\nutil.inherits(JSONParseStream, Transform);\n\n// Gets \\n-delimited JSON string data, and emits the parsed objects\nfunction JSONParseStream(options) {\n  if (!(this instanceof JSONParseStream))\n    return new JSONParseStream(options);\n\n  Transform.call(this, options);\n  this._writableState.objectMode = false;\n  this._readableState.objectMode = true;\n  this._buffer = '';\n  this._decoder = new StringDecoder('utf8');\n}\n\nJSONParseStream.prototype._transform = function(chunk, encoding, cb) {\n  this._buffer += this._decoder.write(chunk);\n  // split on newlines\n  var lines = this._buffer.split(/\\r?\\n/);\n  // keep the last partial line buffered\n  this._buffer = lines.pop();\n  for (var l = 0; l < lines.length; l++) {\n    var line = lines[l];\n    try {\n      var obj = JSON.parse(line);\n    } catch (er) {\n      this.emit('error', er);\n      return;\n    }\n    // push the parsed object out to the readable consumer\n    this.push(obj);\n  }\n  cb();\n};\n\nJSONParseStream.prototype._flush = function(cb) {\n  // Just handle any leftover\n  var rem = this._buffer.trim();\n  if (rem) {\n    try {\n      var obj = JSON.parse(rem);\n    } catch (er) {\n      this.emit('error', er);\n      return;\n    }\n    // push the parsed object out to the readable consumer\n    this.push(obj);\n  }\n  cb();\n};
\n

The state objects contain other useful information for debugging the\nstate of streams in your programs. It is safe to look at them, but\nbeyond setting option flags in the constructor, it is not safe to\nmodify them.\n\n\n

\n", "type": "misc", "displayName": "State Objects" } ] } ], "examples": [ { "textRaw": "Class: stream.Readable", "type": "example", "name": "stream.Readable", "desc": "

stream.Readable is an abstract class designed to be extended with an\nunderlying implementation of the [_read(size)][] method.\n\n

\n

Please see above under [API for Stream Consumers][] for how to consume\nstreams in your programs. What follows is an explanation of how to\nimplement Readable streams in your programs.\n\n

\n

Example: A Counting Stream

\n

This is a basic example of a Readable stream. It emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.\n\n

\n
var Readable = require('stream').Readable;\nvar util = require('util');\nutil.inherits(Counter, Readable);\n\nfunction Counter(opt) {\n  Readable.call(this, opt);\n  this._max = 1000000;\n  this._index = 1;\n}\n\nCounter.prototype._read = function() {\n  var i = this._index++;\n  if (i > this._max)\n    this.push(null);\n  else {\n    var str = '' + i;\n    var buf = new Buffer(str, 'ascii');\n    this.push(buf);\n  }\n};
\n

Example: SimpleProtocol v1 (Sub-optimal)

\n

This is similar to the parseHeader function described above, but\nimplemented as a custom stream. Also, note that this implementation\ndoes not convert the incoming data to a string.\n\n

\n

However, this would be better implemented as a [Transform][] stream. See\nbelow for a better implementation.\n\n

\n
// A parser for a simple data protocol.\n// The "header" is a JSON object, followed by 2 \\n characters, and\n// then a message body.\n//\n// NOTE: This can be done more simply as a Transform stream!\n// Using Readable directly for this is sub-optimal.  See the\n// alternative example below under the Transform section.\n\nvar Readable = require('stream').Readable;\nvar util = require('util');\n\nutil.inherits(SimpleProtocol, Readable);\n\nfunction SimpleProtocol(source, options) {\n  if (!(this instanceof SimpleProtocol))\n    return new SimpleProtocol(source, options);\n\n  Readable.call(this, options);\n  this._inBody = false;\n  this._sawFirstCr = false;\n\n  // source is a readable stream, such as a socket or file\n  this._source = source;\n\n  var self = this;\n  source.on('end', function() {\n    self.push(null);\n  });\n\n  // give it a kick whenever the source is readable\n  // read(0) will not consume any bytes\n  source.on('readable', function() {\n    self.read(0);\n  });\n\n  this._rawHeader = [];\n  this.header = null;\n}\n\nSimpleProtocol.prototype._read = function(n) {\n  if (!this._inBody) {\n    var chunk = this._source.read();\n\n    // if the source doesn't have data, we don't have data yet.\n    if (chunk === null)\n      return this.push('');\n\n    // check if the chunk has a \\n\\n\n    var split = -1;\n    for (var i = 0; i < chunk.length; i++) {\n      if (chunk[i] === 10) { // '\\n'\n        if (this._sawFirstCr) {\n          split = i;\n          break;\n        } else {\n          this._sawFirstCr = true;\n        }\n      } else {\n        this._sawFirstCr = false;\n      }\n    }\n\n    if (split === -1) {\n      // still waiting for the \\n\\n\n      // stash the chunk, and try again.\n      this._rawHeader.push(chunk);\n      this.push('');\n    } else {\n      this._inBody = true;\n      var h = chunk.slice(0, split);\n      this._rawHeader.push(h);\n      var header = Buffer.concat(this._rawHeader).toString();\n      try {\n        this.header = JSON.parse(header);\n      } catch (er) {\n        this.emit('error', new Error('invalid simple protocol data'));\n        return;\n      }\n      // now, because we got some extra data, unshift the rest\n      // back into the read queue so that our consumer will see it.\n      var b = chunk.slice(split);\n      this.unshift(b);\n\n      // and let them know that we are done parsing the header.\n      this.emit('header', this.header);\n    }\n  } else {\n    // from there on, just provide the data to our consumer.\n    // careful not to push(null), since that would indicate EOF.\n    var chunk = this._source.read();\n    if (chunk) this.push(chunk);\n  }\n};\n\n// Usage:\n// var parser = new SimpleProtocol(source);\n// Now parser is a readable stream that will emit 'header'\n// with the parsed header data.
\n", "methods": [ { "textRaw": "new stream.Readable([options])", "type": "method", "name": "Readable", "signatures": [ { "params": [ { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`highWaterMark` {Number} The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb ", "name": "highWaterMark", "type": "Number", "desc": "The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. Default=16kb" }, { "textRaw": "`encoding` {String} If specified, then buffers will be decoded to strings using the specified encoding. Default=null ", "name": "encoding", "type": "String", "desc": "If specified, then buffers will be decoded to strings using the specified encoding. Default=null" }, { "textRaw": "`objectMode` {Boolean} Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false ", "name": "objectMode", "type": "Boolean", "desc": "Whether this stream should behave as a stream of objects. Meaning that stream.read(n) returns a single value instead of a Buffer of size n. Default=false" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "options", "optional": true } ] } ], "desc": "

In classes that extend the Readable class, make sure to call the\nReadable constructor so that the buffering settings can be properly\ninitialized.\n\n

\n" }, { "textRaw": "readable.\\_read(size)", "type": "method", "name": "\\_read", "signatures": [ { "params": [ { "textRaw": "`size` {Number} Number of bytes to read asynchronously ", "name": "size", "type": "Number", "desc": "Number of bytes to read asynchronously" } ] }, { "params": [ { "name": "size" } ] } ], "desc": "

Note: Implement this function, but do NOT call it directly.\n\n

\n

This function should NOT be called directly. It should be implemented\nby child classes, and only called by the internal Readable class\nmethods.\n\n

\n

All Readable stream implementations must provide a _read method to\nfetch data from the underlying resource.\n\n

\n

This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n

\n

When data is available, put it into the read queue by calling\nreadable.push(chunk). If push returns false, then you should stop\nreading. When _read is called again, you should start pushing more\ndata.\n\n

\n

The size argument is advisory. Implementations where a "read" is a\nsingle call that returns data can use this to know how much data to\nfetch. Implementations where that is not relevant, such as TCP or\nTLS, may ignore this argument, and simply provide data whenever it\nbecomes available. There is no need, for example to "wait" until\nsize bytes are available before calling [stream.push(chunk)][].\n\n

\n" }, { "textRaw": "readable.push(chunk, [encoding])", "type": "method", "name": "push", "signatures": [ { "return": { "textRaw": "return {Boolean} Whether or not more pushes should be performed ", "name": "return", "type": "Boolean", "desc": "Whether or not more pushes should be performed" }, "params": [ { "textRaw": "`chunk` {Buffer | null | String} Chunk of data to push into the read queue ", "name": "chunk", "type": "Buffer | null | String", "desc": "Chunk of data to push into the read queue" }, { "textRaw": "`encoding` {String} Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'` ", "name": "encoding", "type": "String", "desc": "Encoding of String chunks. Must be a valid Buffer encoding, such as `'utf8'` or `'ascii'`", "optional": true } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ], "desc": "

Note: This function should be called by Readable implementors, NOT\nby consumers of Readable streams.\n\n

\n

The _read() function will not be called again until at least one\npush(chunk) call is made.\n\n

\n

The Readable class works by putting data into a read queue to be\npulled out later by calling the read() method when the 'readable'\nevent fires.\n\n

\n

The push() method will explicitly insert some data into the read\nqueue. If it is called with null then it will signal the end of the\ndata (EOF).\n\n

\n

This API is designed to be as flexible as possible. For example,\nyou may be wrapping a lower-level source which has some sort of\npause/resume mechanism, and a data callback. In those cases, you\ncould wrap the low-level source object by doing something like this:\n\n

\n
// source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nutil.inherits(SourceWrapper, Readable);\n\nfunction SourceWrapper(options) {\n  Readable.call(this, options);\n\n  this._source = getLowlevelSourceObject();\n  var self = this;\n\n  // Every time there's data, we push it into the internal buffer.\n  this._source.ondata = function(chunk) {\n    // if push() returns false, then we need to stop reading from source\n    if (!self.push(chunk))\n      self._source.readStop();\n  };\n\n  // When the source ends, we push the EOF-signalling `null` chunk\n  this._source.onend = function() {\n    self.push(null);\n  };\n}\n\n// _read will be called when the stream wants to pull more data in\n// the advisory size argument is ignored in this case.\nSourceWrapper.prototype._read = function(size) {\n  this._source.readStart();\n};
\n" } ] } ], "type": "module", "displayName": "Stream" }, { "textRaw": "Crypto", "name": "crypto", "desc": "
Stability: 2 - Unstable; API changes are being discussed for\nfuture versions.  Breaking changes will be minimized.  See below.
\n

Use require('crypto') to access this module.\n\n

\n

The crypto module offers a way of encapsulating secure credentials to be\nused as part of a secure HTTPS net or http connection.\n\n

\n

It also offers a set of wrappers for OpenSSL's hash, hmac, cipher,\ndecipher, sign and verify methods.\n\n\n

\n", "methods": [ { "textRaw": "crypto.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

Returns an array with the names of the supported ciphers.\n\n

\n

Example:\n\n

\n
var ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getHashes()", "type": "method", "name": "getHashes", "desc": "

Returns an array with the names of the supported hash algorithms.\n\n

\n

Example:\n\n

\n
var hashes = crypto.getHashes();\nconsole.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.createCredentials(details)", "type": "method", "name": "createCredentials", "desc": "

Creates a credentials object, with the optional details being a\ndictionary with keys:\n\n

\n\n

If no 'ca' details are given, then node.js will use the default\npublicly trusted list of CAs as given in\n

\n

http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.\n\n\n

\n", "signatures": [ { "params": [ { "name": "details" } ] } ] }, { "textRaw": "crypto.createHash(algorithm)", "type": "method", "name": "createHash", "desc": "

Creates and returns a hash object, a cryptographic hash with the given\nalgorithm which can be used to generate hash digests.\n\n

\n

algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha1', 'md5',\n'sha256', 'sha512', etc. On recent releases, openssl\nlist-message-digest-algorithms will display the available digest\nalgorithms.\n\n

\n

Example: this program that takes the sha1 sum of a file\n\n

\n
var filename = process.argv[2];\nvar crypto = require('crypto');\nvar fs = require('fs');\n\nvar shasum = crypto.createHash('sha1');\n\nvar s = fs.ReadStream(filename);\ns.on('data', function(d) {\n  shasum.update(d);\n});\n\ns.on('end', function() {\n  var d = shasum.digest('hex');\n  console.log(d + '  ' + filename);\n});
\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createHmac(algorithm, key)", "type": "method", "name": "createHmac", "desc": "

Creates and returns a hmac object, a cryptographic hmac with the given\nalgorithm and key.\n\n

\n

It is a stream that is both readable and writable. The\nwritten data is used to compute the hmac. Once the writable side of\nthe stream is ended, use the read() method to get the computed\ndigest. The legacy update and digest methods are also supported.\n\n

\n

algorithm is dependent on the available algorithms supported by\nOpenSSL - see createHash above. key is the hmac key to be used.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" } ] } ] }, { "textRaw": "crypto.createCipher(algorithm, password)", "type": "method", "name": "createCipher", "desc": "

Creates and returns a cipher object, with the given algorithm and\npassword.\n\n

\n

algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent releases, openssl list-cipher-algorithms will display the\navailable cipher algorithms. password is used to derive key and IV,\nwhich must be a 'binary' encoded string or a buffer.\n\n

\n

It is a stream that is both readable and writable. The\nwritten data is used to compute the hash. Once the writable side of\nthe stream is ended, use the read() method to get the enciphered\ncontents. The legacy update and final methods are also supported.\n\n

\n

Note: createCipher derives keys with the OpenSSL function [EVP_BytesToKey][]\nwith the digest algorithm set to MD5, one iteration, and no salt. The lack of\nsalt allows dictionary attacks as the same password always creates the same key.\nThe low iteration count and non-cryptographically secure hash algorithm allow\npasswords to be tested very rapidly.\n\n

\n

In line with OpenSSL's recommendation to use pbkdf2 instead of EVP_BytesToKey it\nis recommended you derive a key and iv yourself with [crypto.pbkdf2][] and to\nthen use [createCipheriv()][] to create the cipher stream.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createCipheriv(algorithm, key, iv)", "type": "method", "name": "createCipheriv", "desc": "

Creates and returns a cipher object, with the given algorithm, key and\niv.\n\n

\n

algorithm is the same as the argument to createCipher(). key is\nthe raw key used by the algorithm. iv is an initialization\nvector.\n\n

\n

key and iv must be 'binary' encoded strings or\nbuffers.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createDecipher(algorithm, password)", "type": "method", "name": "createDecipher", "desc": "

Creates and returns a decipher object, with the given algorithm and\nkey. This is the mirror of the [createCipher()][] above.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createDecipheriv(algorithm, key, iv)", "type": "method", "name": "createDecipheriv", "desc": "

Creates and returns a decipher object, with the given algorithm, key\nand iv. This is the mirror of the [createCipheriv()][] above.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createSign(algorithm)", "type": "method", "name": "createSign", "desc": "

Creates and returns a signing object, with the given algorithm. On\nrecent OpenSSL releases, openssl list-public-key-algorithms will\ndisplay the available signing algorithms. Examples are 'RSA-SHA256'.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createVerify(algorithm)", "type": "method", "name": "createVerify", "desc": "

Creates and returns a verification object, with the given algorithm.\nThis is the mirror of the signing object above.\n\n

\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime_length)", "type": "method", "name": "createDiffieHellman", "desc": "

Creates a Diffie-Hellman key exchange object and generates a prime of\nthe given bit length. The generator used is 2.\n\n

\n", "signatures": [ { "params": [ { "name": "prime_length" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime, [encoding])", "type": "method", "name": "createDiffieHellman", "desc": "

Creates a Diffie-Hellman key exchange object using the supplied prime.\nThe generator used is 2. Encoding can be 'binary', 'hex', or\n'base64'. If no encoding is specified, then a buffer is expected.\n\n

\n", "signatures": [ { "params": [ { "name": "prime" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "crypto.getDiffieHellman(group_name)", "type": "method", "name": "getDiffieHellman", "desc": "

Creates a predefined Diffie-Hellman key exchange object. The\nsupported groups are: 'modp1', 'modp2', 'modp5' (defined in [RFC\n2412][]) and 'modp14', 'modp15', 'modp16', 'modp17',\n'modp18' (defined in [RFC 3526][]). The returned object mimics the\ninterface of objects created by [crypto.createDiffieHellman()][]\nabove, but will not allow to change the keys (with\n[diffieHellman.setPublicKey()][] for example). The advantage of using\nthis routine is that the parties don't have to generate nor exchange\ngroup modulus beforehand, saving both processor and communication\ntime.\n\n

\n

Example (obtaining a shared secret):\n\n

\n
var crypto = require('crypto');\nvar alice = crypto.getDiffieHellman('modp5');\nvar bob = crypto.getDiffieHellman('modp5');\n\nalice.generateKeys();\nbob.generateKeys();\n\nvar alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nvar bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* alice_secret and bob_secret should be the same */\nconsole.log(alice_secret == bob_secret);
\n", "signatures": [ { "params": [ { "name": "group_name" } ] } ] }, { "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen, callback)", "type": "method", "name": "pbkdf2", "desc": "

Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive\na key of given length from the given password, salt and iterations.\nThe callback gets two arguments (err, derivedKey).\n\n

\n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "callback" } ] } ] }, { "textRaw": "crypto.pbkdf2Sync(password, salt, iterations, keylen)", "type": "method", "name": "pbkdf2Sync", "desc": "

Synchronous PBKDF2 function. Returns derivedKey or throws error.\n\n

\n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" } ] } ] }, { "textRaw": "crypto.randomBytes(size, [callback])", "type": "method", "name": "randomBytes", "desc": "

Generates cryptographically strong pseudo-random data. Usage:\n\n

\n
// async\ncrypto.randomBytes(256, function(ex, buf) {\n  if (ex) throw ex;\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n});\n\n// sync\ntry {\n  var buf = crypto.randomBytes(256);\n  console.log('Have %d bytes of random data: %s', buf.length, buf);\n} catch (ex) {\n  // handle error\n  // most likely, entropy sources are drained\n}
\n

NOTE: Will throw error or invoke callback with error, if there is not enough\naccumulated entropy to generate cryptographically strong data. In other words,\ncrypto.randomBytes without callback will not block even if all entropy sources\nare drained.\n\n

\n", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "crypto.pseudoRandomBytes(size, [callback])", "type": "method", "name": "pseudoRandomBytes", "desc": "

Generates non-cryptographically strong pseudo-random data. The data\nreturned will be unique if it is sufficiently long, but is not\nnecessarily unpredictable. For this reason, the output of this\nfunction should never be used where unpredictability is important,\nsuch as in the generation of encryption keys.\n\n

\n

Usage is otherwise identical to crypto.randomBytes.\n\n

\n", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: Hash", "type": "class", "name": "Hash", "desc": "

The class for creating hash digests of data.\n\n

\n

It is a stream that is both readable and writable. The\nwritten data is used to compute the hash. Once the writable side of\nthe stream is ended, use the read() method to get the computed hash\ndigest. The legacy update and digest methods are also supported.\n\n

\n

Returned by crypto.createHash.\n\n

\n", "methods": [ { "textRaw": "hash.update(data, [input_encoding])", "type": "method", "name": "update", "desc": "

Updates the hash content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'binary'. If no encoding is provided and the input is a string an\nencoding of 'binary' is enforced. If data is a Buffer then\ninput_encoding is ignored.\n\n

\n

This can be called many times with new data as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] }, { "textRaw": "hash.digest([encoding])", "type": "method", "name": "digest", "desc": "

Calculates the digest of all of the passed data to be hashed. The\nencoding can be 'hex', 'binary' or 'base64'. If no encoding\nis provided, then a buffer is returned.\n\n

\n

Note: hash object can not be used after digest() method has been\ncalled.\n\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "desc": "

Class for creating cryptographic hmac content.\n\n

\n

Returned by crypto.createHmac.\n\n

\n", "methods": [ { "textRaw": "hmac.update(data)", "type": "method", "name": "update", "desc": "

Update the hmac content with the given data. This can be called\nmany times with new data as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "hmac.digest([encoding])", "type": "method", "name": "digest", "desc": "

Calculates the digest of all of the passed data to the hmac. The\nencoding can be 'hex', 'binary' or 'base64'. If no encoding\nis provided, then a buffer is returned.\n\n

\n

Note: hmac object can not be used after digest() method has been\ncalled.\n\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Cipher", "type": "class", "name": "Cipher", "desc": "

Class for encrypting data.\n\n

\n

Returned by crypto.createCipher and crypto.createCipheriv.\n\n

\n

Cipher objects are streams that are both readable and\nwritable. The written plain text data is used to produce the\nencrypted data on the readable side. The legacy update and final\nmethods are also supported.\n\n

\n", "methods": [ { "textRaw": "cipher.update(data, [input_encoding], [output_encoding])", "type": "method", "name": "update", "desc": "

Updates the cipher with data, the encoding of which is given in\ninput_encoding and can be 'utf8', 'ascii' or 'binary'. If no\nencoding is provided, then a buffer is expected.\nIf data is a Buffer then input_encoding is ignored.\n\n

\n

The output_encoding specifies the output format of the enciphered\ndata, and can be 'binary', 'base64' or 'hex'. If no encoding is\nprovided, then a buffer is returned.\n\n

\n

Returns the enciphered contents, and can be called many times with new\ndata as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.final([output_encoding])", "type": "method", "name": "final", "desc": "

Returns any remaining enciphered contents, with output_encoding\nbeing one of: 'binary', 'base64' or 'hex'. If no encoding is\nprovided, then a buffer is returned.\n\n

\n

Note: cipher object can not be used after final() method has been\ncalled.\n\n

\n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "desc": "

You can disable automatic padding of the input data to block size. If\nauto_padding is false, the length of the entire input data must be a\nmultiple of the cipher's block size or final will fail. Useful for\nnon-standard padding, e.g. using 0x0 instead of PKCS padding. You\nmust call this before cipher.final.\n\n\n

\n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] } ] }, { "textRaw": "Class: Decipher", "type": "class", "name": "Decipher", "desc": "

Class for decrypting data.\n\n

\n

Returned by crypto.createDecipher and crypto.createDecipheriv.\n\n

\n

Decipher objects are streams that are both readable and\nwritable. The written enciphered data is used to produce the\nplain-text data on the the readable side. The legacy update and\nfinal methods are also supported.\n\n

\n", "methods": [ { "textRaw": "decipher.update(data, [input_encoding], [output_encoding])", "type": "method", "name": "update", "desc": "

Updates the decipher with data, which is encoded in 'binary',\n'base64' or 'hex'. If no encoding is provided, then a buffer is\nexpected.\nIf data is a Buffer then input_encoding is ignored.\n\n

\n

The output_decoding specifies in what format to return the\ndeciphered plaintext: 'binary', 'ascii' or 'utf8'. If no\nencoding is provided, then a buffer is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.final([output_encoding])", "type": "method", "name": "final", "desc": "

Returns any remaining plaintext which is deciphered, with\noutput_encoding being one of: 'binary', 'ascii' or 'utf8'. If\nno encoding is provided, then a buffer is returned.\n\n

\n

Note: decipher object can not be used after final() method has been\ncalled.\n\n

\n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "desc": "

You can disable auto padding if the data has been encrypted without\nstandard block padding to prevent decipher.final from checking and\nremoving it. Can only work if the input data's length is a multiple of\nthe ciphers block size. You must call this before streaming data to\ndecipher.update.\n\n

\n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "desc": "

Class for generating signatures.\n\n

\n

Returned by crypto.createSign.\n\n

\n

Sign objects are writable streams. The written data is\nused to generate the signature. Once all of the data has been\nwritten, the sign method will return the signature. The legacy\nupdate method is also supported.\n\n

\n", "methods": [ { "textRaw": "sign.update(data)", "type": "method", "name": "update", "desc": "

Updates the sign object with data. This can be called many times\nwith new data as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "sign.sign(private_key, [output_format])", "type": "method", "name": "sign", "desc": "

Calculates the signature on all the updated data passed through the\nsign. private_key is a string containing the PEM encoded private\nkey for signing.\n\n

\n

Returns the signature in output_format which can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nreturned.\n\n

\n

Note: sign object can not be used after sign() method has been\ncalled.\n\n

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "output_format", "optional": true } ] } ] } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "desc": "

Class for verifying signatures.\n\n

\n

Returned by crypto.createVerify.\n\n

\n

Verify objects are writable streams. The written data\nis used to validate against the supplied signature. Once all of the\ndata has been written, the verify method will return true if the\nsupplied signature is valid. The legacy update method is also\nsupported.\n\n

\n", "methods": [ { "textRaw": "verifier.update(data)", "type": "method", "name": "update", "desc": "

Updates the verifier object with data. This can be called many times\nwith new data as it is streamed.\n\n

\n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "verifier.verify(object, signature, [signature_format])", "type": "method", "name": "verify", "desc": "

Verifies the signed data by using the object and signature.\nobject is a string containing a PEM encoded object, which can be\none of RSA public key, DSA public key, or X.509 certificate.\nsignature is the previously calculated signature for the data, in\nthe signature_format which can be 'binary', 'hex' or 'base64'.\nIf no encoding is specified, then a buffer is expected.\n\n

\n

Returns true or false depending on the validity of the signature for\nthe data and public key.\n\n

\n

Note: verifier object can not be used after verify() method has been\ncalled.\n\n

\n", "signatures": [ { "params": [ { "name": "object" }, { "name": "signature" }, { "name": "signature_format", "optional": true } ] } ] } ] }, { "textRaw": "Class: DiffieHellman", "type": "class", "name": "DiffieHellman", "desc": "

The class for creating Diffie-Hellman key exchanges.\n\n

\n

Returned by crypto.createDiffieHellman.\n\n

\n", "methods": [ { "textRaw": "diffieHellman.generateKeys([encoding])", "type": "method", "name": "generateKeys", "desc": "

Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party. Encoding can be 'binary', 'hex',\nor 'base64'. If no encoding is provided, then a buffer is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])", "type": "method", "name": "computeSecret", "desc": "

Computes the shared secret using other_public_key as the other\nparty's public key and returns the computed shared secret. Supplied\nkey is interpreted using specified input_encoding, and secret is\nencoded using specified output_encoding. Encodings can be\n'binary', 'hex', or 'base64'. If the input encoding is not\nprovided, then a buffer is expected.\n\n

\n

If no output encoding is given, then a buffer is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "other_public_key" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrime([encoding])", "type": "method", "name": "getPrime", "desc": "

Returns the Diffie-Hellman prime in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getGenerator([encoding])", "type": "method", "name": "getGenerator", "desc": "

Returns the Diffie-Hellman generator in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPublicKey([encoding])", "type": "method", "name": "getPublicKey", "desc": "

Returns the Diffie-Hellman public key in the specified encoding, which\ncan be 'binary', 'hex', or 'base64'. If no encoding is provided,\nthen a buffer is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "desc": "

Returns the Diffie-Hellman private key in the specified encoding,\nwhich can be 'binary', 'hex', or 'base64'. If no encoding is\nprovided, then a buffer is returned.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPublicKey(public_key, [encoding])", "type": "method", "name": "setPublicKey", "desc": "

Sets the Diffie-Hellman public key. Key encoding can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nexpected.\n\n

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPrivateKey(private_key, [encoding])", "type": "method", "name": "setPrivateKey", "desc": "

Sets the Diffie-Hellman private key. Key encoding can be 'binary',\n'hex' or 'base64'. If no encoding is provided, then a buffer is\nexpected.\n\n

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] } ] } ], "properties": [ { "textRaw": "crypto.DEFAULT_ENCODING", "name": "DEFAULT_ENCODING", "desc": "

The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer', which makes it default\nto using Buffer objects. This is here to make the crypto module more\neasily compatible with legacy programs that expected 'binary' to be\nthe default encoding.\n\n

\n

Note that new programs will probably expect buffers, so only use this\nas a temporary measure.\n\n

\n" } ], "modules": [ { "textRaw": "Recent API Changes", "name": "recent_api_changes", "desc": "

The Crypto module was added to Node before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data.\n\n

\n

As such, the streaming classes don't have the typical methods found on\nother Node classes, and many methods accepted and returned\nBinary-encoded strings by default rather than Buffers. This was\nchanged to use Buffers by default instead.\n\n

\n

This is a breaking change for some use cases, but not all.\n\n

\n

For example, if you currently use the default arguments to the Sign\nclass, and then pass the results to the Verify class, without ever\ninspecting the data, then it will continue to work as before. Where\nyou once got a binary string and then presented the binary string to\nthe Verify object, you'll now get a Buffer, and present the Buffer to\nthe Verify object.\n\n

\n

However, if you were doing things with the string data that will not\nwork properly on Buffers (such as, concatenating them, storing in\ndatabases, etc.), or you are passing binary strings to the crypto\nfunctions without an encoding argument, then you will need to start\nproviding encoding arguments to specify which encoding you'd like to\nuse. To switch to the previous style of using binary strings by\ndefault, set the crypto.DEFAULT_ENCODING field to 'binary'. Note\nthat new programs will probably expect buffers, so only use this as a\ntemporary measure.\n\n\n

\n", "type": "module", "displayName": "Recent API Changes" } ], "type": "module", "displayName": "Crypto" }, { "textRaw": "TLS (SSL)", "name": "tls_(ssl)", "stability": 3, "stabilityText": "Stable", "desc": "

Use require('tls') to access this module.\n\n

\n

The tls module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\n\n

\n

TLS/SSL is a public/private key infrastructure. Each client and each\nserver must have a private key. A private key is created like this:\n\n

\n
openssl genrsa -out ryans-key.pem 2048
\n

All servers and some clients need to have a certificate. Certificates are public\nkeys signed by a Certificate Authority or self-signed. The first step to\ngetting a certificate is to create a "Certificate Signing Request" (CSR)\nfile. This is done with:\n\n

\n
openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
\n

To create a self-signed certificate with the CSR, do this:\n\n

\n
openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
\n

Alternatively you can send the CSR to a Certificate Authority for signing.\n\n

\n

(TODO: docs on creating a CA, for now interested users should just look at\ntest/fixtures/keys/Makefile in the Node source code)\n\n

\n

To create .pfx or .p12, do this:\n\n

\n
openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n    -certfile ca-cert.pem -out agent5.pfx
\n\n", "modules": [ { "textRaw": "Protocol support", "name": "protocol_support", "desc": "

Node.js is compiled with SSLv2 and SSLv3 protocol support by default, but these\nprotocols are disabled. They are considered insecure and could be easily\ncompromised as was shown by [CVE-2014-3566][]. However, in some situations, it\nmay cause problems with legacy clients/servers (such as Internet Explorer 6).\nIf you wish to enable SSLv2 or SSLv3, run node with the --enable-ssl2 or\n--enable-ssl3 flag respectively. In future versions of Node.js SSLv2 and\nSSLv3 will not be compiled in by default.\n\n

\n

There is a way to force node into using SSLv3 or SSLv2 only mode by explicitly\nspecifying secureProtocol to 'SSLv3_method' or 'SSLv2_method'.\n\n

\n

The default protocol method Node.js uses is SSLv23_method which would be more\naccurately named AutoNegotiate_method. This method will try and negotiate\nfrom the highest level down to whatever the client supports. To provide a\nsecure default, Node.js (since v0.10.33) explicitly disables the use of SSLv3\nand SSLv2 by setting the secureOptions to be\nSSL_OP_NO_SSLv3|SSL_OP_NO_SSLv2 (again, unless you have passed\n--enable-ssl3, or --enable-ssl2, or SSLv3_method as secureProtocol).\n\n

\n

If you have set secureOptions to anything, we will not override your\noptions.\n\n

\n

The ramifications of this behavior change:\n\n

\n\n", "type": "module", "displayName": "Protocol support" } ], "miscs": [ { "textRaw": "Client-initiated renegotiation attack mitigation", "name": "Client-initiated renegotiation attack mitigation", "type": "misc", "desc": "

The TLS protocol lets the client renegotiate certain aspects of the TLS session.\nUnfortunately, session renegotiation requires a disproportional amount of\nserver-side resources, which makes it a potential vector for denial-of-service\nattacks.\n\n

\n

To mitigate this, renegotiations are limited to three times every 10 minutes. An\nerror is emitted on the [CleartextStream][] instance when the threshold is\nexceeded. The limits are configurable:\n\n

\n\n

Don't change the defaults unless you know what you are doing.\n\n

\n

To test your server, connect to it with openssl s_client -connect address:port\nand tap R<CR> (that's the letter R followed by a carriage return) a few\ntimes.\n\n\n

\n" }, { "textRaw": "NPN and SNI", "name": "NPN and SNI", "type": "misc", "desc": "

NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS\nhandshake extensions allowing you:\n\n

\n\n" } ], "methods": [ { "textRaw": "tls.getCiphers()", "type": "method", "name": "getCiphers", "desc": "

Returns an array with the names of the supported SSL ciphers.\n\n

\n

Example:\n\n

\n
var ciphers = tls.getCiphers();\nconsole.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "tls.createServer(options, [secureConnectionListener])", "type": "method", "name": "createServer", "desc": "

Creates a new [tls.Server][]. The connectionListener argument is\nautomatically set as a listener for the [secureConnection][] event. The\noptions object has these possibilities:\n\n

\n\n
`AES128-GCM-SHA256` is used when node.js is linked against OpenSSL 1.0.1\nor newer and the client speaks TLS 1.2, RC4 is used as a secure fallback.\n\n**NOTE**: Previous revisions of this section suggested `AES256-SHA` as an\nacceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore\nsusceptible to BEAST attacks. Do *not* use it.
\n\n

Here is a simple example echo server:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  key: fs.readFileSync('server-key.pem'),\n  cert: fs.readFileSync('server-cert.pem'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n  // This is necessary only if the client uses the self-signed certificate.\n  ca: [ fs.readFileSync('client-cert.pem') ]\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx'),\n\n  // This is necessary only if using the client certificate authentication.\n  requestCert: true,\n\n};\n\nvar server = tls.createServer(options, function(cleartextStream) {\n  console.log('server connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  cleartextStream.write("welcome!\\n");\n  cleartextStream.setEncoding('utf8');\n  cleartextStream.pipe(cleartextStream);\n});\nserver.listen(8000, function() {\n  console.log('server bound');\n});
\n

You can test this server by connecting to it with openssl s_client:\n\n\n

\n
openssl s_client -connect 127.0.0.1:8000
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "secureConnectionListener", "optional": true } ] } ] }, { "textRaw": "tls.connect(options, [callback])", "type": "method", "name": "connect", "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [CleartextStream][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.connect(port, [host], [options], [callback])", "type": "method", "name": "connect", "desc": "

Creates a new client connection to the given port and host (old API) or\noptions.port and options.host. (If host is omitted, it defaults to\nlocalhost.) options should be an object which specifies:\n\n

\n\n

The callback parameter will be added as a listener for the\n['secureConnect'][] event.\n\n

\n

tls.connect() returns a [CleartextStream][] object.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  // These are necessary only if using the client certificate authentication\n  key: fs.readFileSync('client-key.pem'),\n  cert: fs.readFileSync('client-cert.pem'),\n\n  // This is necessary only if the server uses the self-signed certificate\n  ca: [ fs.readFileSync('server-cert.pem') ]\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n

Or\n\n

\n
var tls = require('tls');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('client.pfx')\n};\n\nvar cleartextStream = tls.connect(8000, options, function() {\n  console.log('client connected',\n              cleartextStream.authorized ? 'authorized' : 'unauthorized');\n  process.stdin.pipe(cleartextStream);\n  process.stdin.resume();\n});\ncleartextStream.setEncoding('utf8');\ncleartextStream.on('data', function(data) {\n  console.log(data);\n});\ncleartextStream.on('end', function() {\n  server.close();\n});
\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])", "type": "method", "name": "createSecurePair", "desc": "

Creates a new secure pair object with two streams, one of which reads/writes\nencrypted data, and one reads/writes cleartext data.\nGenerally the encrypted one is piped to/from an incoming encrypted data stream,\nand the cleartext one is used as a replacement for the initial encrypted stream.\n\n

\n\n

tls.createSecurePair() returns a SecurePair object with [cleartext][] and\nencrypted stream properties.\n\n

\n", "signatures": [ { "params": [ { "name": "credentials", "optional": true }, { "name": "isServer", "optional": true }, { "name": "requestCert", "optional": true }, { "name": "rejectUnauthorized", "optional": true } ] } ] } ], "properties": [ { "textRaw": "tls.SLAB_BUFFER_SIZE", "name": "SLAB_BUFFER_SIZE", "desc": "

Size of slab buffer used by all tls servers and clients.\nDefault: 10 * 1024 * 1024.\n\n\n

\n

Don't change the defaults unless you know what you are doing.\n\n\n

\n" } ], "classes": [ { "textRaw": "Class: SecurePair", "type": "class", "name": "SecurePair", "desc": "

Returned by tls.createSecurePair.\n\n

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

The event is emitted from the SecurePair once the pair has successfully\nestablished a secure connection.\n\n

\n

Similarly to the checking for the server 'secureConnection' event,\npair.cleartext.authorized should be checked to confirm whether the certificate\nused properly authorized.\n\n

\n", "params": [] } ] }, { "textRaw": "Class: tls.Server", "type": "class", "name": "tls.Server", "desc": "

This class is a subclass of net.Server and has the same methods on it.\nInstead of accepting just raw TCP connections, this accepts encrypted\nconnections using TLS or SSL.\n\n

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

function (cleartextStream) {}\n\n

\n

This event is emitted after a new connection has been successfully\nhandshaked. The argument is an instance of [CleartextStream][]. It has all the\ncommon stream methods and events.\n\n

\n

cleartextStream.authorized is a boolean value which indicates if the\nclient has verified by one of the supplied certificate authorities for the\nserver. If cleartextStream.authorized is false, then\ncleartextStream.authorizationError is set to describe how authorization\nfailed. Implied but worth mentioning: depending on the settings of the TLS\nserver, you unauthorized connections may be accepted.\ncleartextStream.npnProtocol is a string containing selected NPN protocol.\ncleartextStream.servername is a string containing servername requested with\nSNI.\n\n\n

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

function (exception, securePair) { }\n\n

\n

When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\n\n

\n

securePair is the tls.SecurePair that the error originated from.\n\n\n

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

function (sessionId, sessionData) { }\n\n

\n

Emitted on creation of TLS session. May be used to store sessions in external\nstorage.\n\n\n

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

function (sessionId, callback) { }\n\n

\n

Emitted when client wants to resume previous TLS session. Event listener may\nperform lookup in external storage using given sessionId, and invoke\ncallback(null, sessionData) once finished. If session can't be resumed\n(i.e. doesn't exist in storage) one may call callback(null, null). Calling\ncallback(err) will terminate incoming connection and destroy socket.\n\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [host], [callback])", "type": "method", "name": "listen", "desc": "

Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

\n

This function is asynchronous. The last parameter callback will be called\nwhen the server has been bound.\n\n

\n

See net.Server for more information.\n\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.close()", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections. This function is\nasynchronous, the server is finally closed when the server emits a 'close'\nevent.\n\n

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

Returns the bound address, the address family name and port of the\nserver as reported by the operating system. See [net.Server.address()][] for\nmore information.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.addContext(hostname, credentials)", "type": "method", "name": "addContext", "desc": "

Add secure context that will be used if client request's SNI hostname is\nmatching passed hostname (wildcards can be used). credentials can contain\nkey, cert and ca.\n\n

\n", "signatures": [ { "params": [ { "name": "hostname" }, { "name": "credentials" } ] } ] } ], "properties": [ { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

Set this property to reject connections when the server's connection count\ngets high.\n\n

\n" }, { "textRaw": "server.connections", "name": "connections", "desc": "

The number of concurrent connections on the server.\n\n\n

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

This is an encrypted stream.\n\n

\n", "properties": [ { "textRaw": "cryptoStream.bytesWritten", "name": "bytesWritten", "desc": "

A proxy to the underlying socket's bytesWritten accessor, this will return\nthe total bytes written to the socket, including the TLS overhead.\n\n

\n" } ] }, { "textRaw": "Class: tls.CleartextStream", "type": "class", "name": "tls.CleartextStream", "desc": "

This is a stream on top of the Encrypted stream that makes it possible to\nread/write an encrypted data as a cleartext data.\n\n

\n

This instance implements a duplex [Stream][] interfaces. It has all the\ncommon stream methods and events.\n\n

\n

A ClearTextStream is the clear member of a SecurePair object.\n\n

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

This event is emitted after a new connection has been successfully handshaked. \nThe listener will be called no matter if the server's certificate was\nauthorized or not. It is up to the user to test cleartextStream.authorized\nto see if the server certificate was signed by one of the specified CAs.\nIf cleartextStream.authorized === false then the error can be found in\ncleartextStream.authorizationError. Also if NPN was used - you can check\ncleartextStream.npnProtocol for negotiated protocol.\n\n

\n", "params": [] } ], "properties": [ { "textRaw": "cleartextStream.authorized", "name": "authorized", "desc": "

A boolean that is true if the peer certificate was signed by one of the\nspecified CAs, otherwise false\n\n

\n" }, { "textRaw": "cleartextStream.authorizationError", "name": "authorizationError", "desc": "

The reason why the peer's certificate has not been verified. This property\nbecomes available only when cleartextStream.authorized === false.\n\n

\n" }, { "textRaw": "cleartextStream.remoteAddress", "name": "remoteAddress", "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" }, { "textRaw": "cleartextStream.remotePort", "name": "remotePort", "desc": "

The numeric representation of the remote port. For example, 443.\n\n

\n" } ], "methods": [ { "textRaw": "cleartextStream.getPeerCertificate()", "type": "method", "name": "getPeerCertificate", "desc": "

Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the field of the certificate.\n\n

\n

Example:\n\n

\n
{ subject: \n   { C: 'UK',\n     ST: 'Acknack Ltd',\n     L: 'Rhys Jones',\n     O: 'node.js',\n     OU: 'Test TLS Certificate',\n     CN: 'localhost' },\n  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  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

If the peer does not provide a certificate, it returns null or an empty\nobject.\n\n

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

Returns an object representing the cipher name and the SSL/TLS\nprotocol version of the current connection.\n\n

\n

Example:\n{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }\n\n

\n

See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in\nhttp://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS for more\ninformation.\n\n

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

Returns the bound address, the address family name and port of the\nunderlying socket as reported by the operating system. Returns an\nobject with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "TLS (SSL)" }, { "textRaw": "StringDecoder", "name": "stringdecoder", "stability": 3, "stabilityText": "Stable", "desc": "

To use this module, do require('string_decoder'). StringDecoder decodes a\nbuffer to a string. It is a simple interface to buffer.toString() but provides\nadditional support for utf8.\n\n

\n
var StringDecoder = require('string_decoder').StringDecoder;\nvar decoder = new StringDecoder('utf8');\n\nvar cent = new Buffer([0xC2, 0xA2]);\nconsole.log(decoder.write(cent));\n\nvar euro = new Buffer([0xE2, 0x82, 0xAC]);\nconsole.log(decoder.write(euro));
\n", "classes": [ { "textRaw": "Class: StringDecoder", "type": "class", "name": "StringDecoder", "desc": "

Accepts a single argument, encoding which defaults to utf8.\n\n

\n", "methods": [ { "textRaw": "decoder.write(buffer)", "type": "method", "name": "write", "desc": "

Returns a decoded string.\n\n

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decoder.end()", "type": "method", "name": "end", "desc": "

Returns any trailing bytes that were left in the buffer.\n\n

\n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "StringDecoder" }, { "textRaw": "File System", "name": "fs", "stability": 3, "stabilityText": "Stable", "desc": "

File I/O is provided by simple wrappers around standard POSIX functions. To\nuse this module do require('fs'). All the methods have asynchronous and\nsynchronous forms.\n\n

\n

The asynchronous form always take a completion callback as its last argument.\nThe arguments passed to the completion callback depend on the method, but the\nfirst argument is always reserved for an exception. If the operation was\ncompleted successfully, then the first argument will be null or undefined.\n\n

\n

When using the synchronous form any exceptions are immediately thrown.\nYou can use try/catch to handle exceptions or allow them to bubble up.\n\n

\n

Here is an example of the asynchronous version:\n\n

\n
var fs = require('fs');\n\nfs.unlink('/tmp/hello', function (err) {\n  if (err) throw err;\n  console.log('successfully deleted /tmp/hello');\n});
\n

Here is the synchronous version:\n\n

\n
var fs = require('fs');\n\nfs.unlinkSync('/tmp/hello')\nconsole.log('successfully deleted /tmp/hello');
\n

With the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:\n\n

\n
fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  console.log('renamed complete');\n});\nfs.stat('/tmp/world', function (err, stats) {\n  if (err) throw err;\n  console.log('stats: ' + JSON.stringify(stats));\n});
\n

It could be that fs.stat is executed before fs.rename.\nThe correct way to do this is to chain the callbacks.\n\n

\n
fs.rename('/tmp/hello', '/tmp/world', function (err) {\n  if (err) throw err;\n  fs.stat('/tmp/world', function (err, stats) {\n    if (err) throw err;\n    console.log('stats: ' + JSON.stringify(stats));\n  });\n});
\n

In busy processes, the programmer is strongly encouraged to use the\nasynchronous versions of these calls. The synchronous versions will block\nthe entire process until they complete--halting all connections.\n\n

\n

Relative path to filename can be used, remember however that this path will be\nrelative to process.cwd().\n\n

\n

Most fs functions let you omit the callback argument. If you do, a default\ncallback is used that ignores errors, but prints a deprecation\nwarning.\n\n

\n

IMPORTANT: Omitting the callback is deprecated. v0.12 will throw the\nerrors as exceptions.\n\n\n

\n", "methods": [ { "textRaw": "fs.rename(oldPath, newPath, callback)", "type": "method", "name": "rename", "desc": "

Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.renameSync(oldPath, newPath)", "type": "method", "name": "renameSync", "desc": "

Synchronous rename(2).\n\n

\n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" } ] } ] }, { "textRaw": "fs.ftruncate(fd, len, callback)", "type": "method", "name": "ftruncate", "desc": "

Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.ftruncateSync(fd, len)", "type": "method", "name": "ftruncateSync", "desc": "

Synchronous ftruncate(2).\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" } ] } ] }, { "textRaw": "fs.truncate(path, len, callback)", "type": "method", "name": "truncate", "desc": "

Asynchronous truncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.truncateSync(path, len)", "type": "method", "name": "truncateSync", "desc": "

Synchronous truncate(2).\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "len" } ] } ] }, { "textRaw": "fs.chown(path, uid, gid, callback)", "type": "method", "name": "chown", "desc": "

Asynchronous chown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chownSync(path, uid, gid)", "type": "method", "name": "chownSync", "desc": "

Synchronous chown(2).\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.fchown(fd, uid, gid, callback)", "type": "method", "name": "fchown", "desc": "

Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchownSync(fd, uid, gid)", "type": "method", "name": "fchownSync", "desc": "

Synchronous fchown(2).\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.lchown(path, uid, gid, callback)", "type": "method", "name": "lchown", "desc": "

Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchownSync(path, uid, gid)", "type": "method", "name": "lchownSync", "desc": "

Synchronous lchown(2).\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" } ] } ] }, { "textRaw": "fs.chmod(path, mode, callback)", "type": "method", "name": "chmod", "desc": "

Asynchronous chmod(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chmodSync(path, mode)", "type": "method", "name": "chmodSync", "desc": "

Synchronous chmod(2).\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.fchmod(fd, mode, callback)", "type": "method", "name": "fchmod", "desc": "

Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchmodSync(fd, mode)", "type": "method", "name": "fchmodSync", "desc": "

Synchronous fchmod(2).\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.lchmod(path, mode, callback)", "type": "method", "name": "lchmod", "desc": "

Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n

\n

Only available on Mac OS X.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchmodSync(path, mode)", "type": "method", "name": "lchmodSync", "desc": "

Synchronous lchmod(2).\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" } ] } ] }, { "textRaw": "fs.stat(path, callback)", "type": "method", "name": "stat", "desc": "

Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. See the fs.Stats\nsection below for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lstat(path, callback)", "type": "method", "name": "lstat", "desc": "

Asynchronous lstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. lstat() is identical to stat(), except that if\npath is a symbolic link, then the link itself is stat-ed, not the file that it\nrefers to.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fstat(fd, callback)", "type": "method", "name": "fstat", "desc": "

Asynchronous fstat(2). The callback gets two arguments (err, stats) where\nstats is a fs.Stats object. fstat() is identical to stat(), except that\nthe file to be stat-ed is specified by the file descriptor fd.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.statSync(path)", "type": "method", "name": "statSync", "desc": "

Synchronous stat(2). Returns an instance of fs.Stats.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.lstatSync(path)", "type": "method", "name": "lstatSync", "desc": "

Synchronous lstat(2). Returns an instance of fs.Stats.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.fstatSync(fd)", "type": "method", "name": "fstatSync", "desc": "

Synchronous fstat(2). Returns an instance of fs.Stats.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.link(srcpath, dstpath, callback)", "type": "method", "name": "link", "desc": "

Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.linkSync(srcpath, dstpath)", "type": "method", "name": "linkSync", "desc": "

Synchronous link(2).\n\n

\n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" } ] } ] }, { "textRaw": "fs.symlink(srcpath, dstpath, [type], callback)", "type": "method", "name": "symlink", "desc": "

Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback.\nThe type argument can be set to 'dir', 'file', or 'junction' (default\nis 'file') and is only available on Windows (ignored on other platforms).\nNote that Windows junction points require the destination path to be absolute. When using\n'junction', the destination argument will automatically be normalized to absolute path.\n\n

\n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "type", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.symlinkSync(srcpath, dstpath, [type])", "type": "method", "name": "symlinkSync", "desc": "

Synchronous symlink(2).\n\n

\n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "type", "optional": true } ] } ] }, { "textRaw": "fs.readlink(path, callback)", "type": "method", "name": "readlink", "desc": "

Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString).\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readlinkSync(path)", "type": "method", "name": "readlinkSync", "desc": "

Synchronous readlink(2). Returns the symbolic link's string value.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.realpath(path, [cache], callback)", "type": "method", "name": "realpath", "desc": "

Asynchronous realpath(2). The callback gets two arguments (err,\nresolvedPath). May use process.cwd to resolve relative paths. cache is an\nobject literal of mapped paths that can be used to force a specific path\nresolution or avoid additional fs.stat calls for known real paths.\n\n

\n

Example:\n\n

\n
var cache = {'/etc':'/private/etc'};\nfs.realpath('/etc/passwd', cache, function (err, resolvedPath) {\n  if (err) throw err;\n  console.log(resolvedPath);\n});
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.realpathSync(path, [cache])", "type": "method", "name": "realpathSync", "desc": "

Synchronous realpath(2). Returns the resolved path.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true } ] } ] }, { "textRaw": "fs.unlink(path, callback)", "type": "method", "name": "unlink", "desc": "

Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.unlinkSync(path)", "type": "method", "name": "unlinkSync", "desc": "

Synchronous unlink(2).\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.rmdir(path, callback)", "type": "method", "name": "rmdir", "desc": "

Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.rmdirSync(path)", "type": "method", "name": "rmdirSync", "desc": "

Synchronous rmdir(2).\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.mkdir(path, [mode], callback)", "type": "method", "name": "mkdir", "desc": "

Asynchronous mkdir(2). No arguments other than a possible exception are given\nto the completion callback. mode defaults to 0777.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.mkdirSync(path, [mode])", "type": "method", "name": "mkdirSync", "desc": "

Synchronous mkdir(2).\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.readdir(path, callback)", "type": "method", "name": "readdir", "desc": "

Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files) where files is an array of\nthe names of the files in the directory excluding '.' and '..'.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readdirSync(path)", "type": "method", "name": "readdirSync", "desc": "

Synchronous readdir(3). Returns an array of filenames excluding '.' and\n'..'.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.close(fd, callback)", "type": "method", "name": "close", "desc": "

Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.closeSync(fd)", "type": "method", "name": "closeSync", "desc": "

Synchronous close(2).\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.open(path, flags, [mode], callback)", "type": "method", "name": "open", "desc": "

Asynchronous file open. See open(2). flags can be:\n\n

\n\n

mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. It defaults to 0666, readable and writeable.\n\n

\n

The callback gets two arguments (err, fd).\n\n

\n

The exclusive flag 'x' (O_EXCL flag in open(2)) ensures that path is newly\ncreated. On POSIX systems, path is considered to exist even if it is a symlink\nto a non-existent file. The exclusive flag may or may not work with network file\nsystems.\n\n

\n

On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.openSync(path, flags, [mode])", "type": "method", "name": "openSync", "desc": "

Synchronous version of fs.open().\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true } ] } ] }, { "textRaw": "fs.utimes(path, atime, mtime, callback)", "type": "method", "name": "utimes", "desc": "

Change file timestamps of the file referenced by the supplied path.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" } ] }, { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.utimesSync(path, atime, mtime)", "type": "method", "name": "utimesSync", "desc": "

Change file timestamps of the file referenced by the supplied path.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "atime" }, { "name": "mtime" } ] } ] }, { "textRaw": "fs.futimes(fd, atime, mtime, callback)", "type": "method", "name": "futimes", "desc": "

Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] }, { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.futimesSync(fd, atime, mtime)", "type": "method", "name": "futimesSync", "desc": "

Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" } ] } ] }, { "textRaw": "fs.fsync(fd, callback)", "type": "method", "name": "fsync", "desc": "

Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fsyncSync(fd)", "type": "method", "name": "fsyncSync", "desc": "

Synchronous fsync(2).\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "fs.write(fd, buffer, offset, length, position, callback)", "type": "method", "name": "write", "desc": "

Write buffer to the file specified by fd.\n\n

\n

offset and length determine the part of the buffer to be written.\n\n

\n

position refers to the offset from the beginning of the file where this data\nshould be written. If position is null, the data will be written at the\ncurrent position.\nSee pwrite(2).\n\n

\n

The callback will be given three arguments (err, written, buffer) where written\nspecifies how many bytes were written from buffer.\n\n

\n

Note that it is unsafe to use fs.write multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream is strongly recommended.\n\n

\n

On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.writeSync(fd, buffer, offset, length, position)", "type": "method", "name": "writeSync", "desc": "

Synchronous version of fs.write(). Returns the number of bytes written.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" } ] } ] }, { "textRaw": "fs.read(fd, buffer, offset, length, position, callback)", "type": "method", "name": "read", "desc": "

Read data from the file specified by fd.\n\n

\n

buffer is the buffer that the data will be written to.\n\n

\n

offset is the offset in the buffer to start writing at.\n\n

\n

length is an integer specifying the number of bytes to read.\n\n

\n

position is an integer specifying where to begin reading from in the file.\nIf position is null, data will be read from the current file position.\n\n

\n

The callback is given the three arguments, (err, bytesRead, buffer).\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.readSync(fd, buffer, offset, length, position)", "type": "method", "name": "readSync", "desc": "

Synchronous version of fs.read. Returns the number of bytesRead.\n\n

\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position" } ] } ] }, { "textRaw": "fs.readFile(filename, [options], callback)", "type": "method", "name": "readFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `null` ", "name": "encoding", "type": "String | Null", "desc": "default = `null`" }, { "textRaw": "`flag` {String} default = `'r'` ", "name": "flag", "type": "String", "desc": "default = `'r'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronously reads the entire contents of a file. Example:\n\n

\n
fs.readFile('/etc/passwd', function (err, data) {\n  if (err) throw err;\n  console.log(data);\n});
\n

The callback is passed two arguments (err, data), where data is the\ncontents of the file.\n\n

\n

If no encoding is specified, then the raw buffer is returned.\n\n\n

\n" }, { "textRaw": "fs.readFileSync(filename, [options])", "type": "method", "name": "readFileSync", "desc": "

Synchronous version of fs.readFile. Returns the contents of the filename.\n\n

\n

If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.\n\n\n

\n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.writeFile(filename, data, [options], callback)", "type": "method", "name": "writeFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`data` {String | Buffer} ", "name": "data", "type": "String | Buffer" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `'utf8'` ", "name": "encoding", "type": "String | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {Number} default = `438` (aka `0666` in Octal) ", "name": "mode", "type": "Number", "desc": "default = `438` (aka `0666` in Octal)" }, { "textRaw": "`flag` {String} default = `'w'` ", "name": "flag", "type": "String", "desc": "default = `'w'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string or a buffer.\n\n

\n

The encoding option is ignored if data is a buffer. It defaults\nto 'utf8'.\n\n

\n

Example:\n\n

\n
fs.writeFile('message.txt', 'Hello Node', function (err) {\n  if (err) throw err;\n  console.log('It\\'s saved!');\n});
\n" }, { "textRaw": "fs.writeFileSync(filename, data, [options])", "type": "method", "name": "writeFileSync", "desc": "

The synchronous version of fs.writeFile.\n\n

\n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.appendFile(filename, data, [options], callback)", "type": "method", "name": "appendFile", "signatures": [ { "params": [ { "textRaw": "`filename` {String} ", "name": "filename", "type": "String" }, { "textRaw": "`data` {String | Buffer} ", "name": "data", "type": "String | Buffer" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`encoding` {String | Null} default = `'utf8'` ", "name": "encoding", "type": "String | Null", "desc": "default = `'utf8'`" }, { "textRaw": "`mode` {Number} default = `438` (aka `0666` in Octal) ", "name": "mode", "type": "Number", "desc": "default = `438` (aka `0666` in Octal)" }, { "textRaw": "`flag` {String} default = `'a'` ", "name": "flag", "type": "String", "desc": "default = `'a'`" } ], "name": "options", "type": "Object", "optional": true }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Asynchronously append data to a file, creating the file if it not yet exists.\ndata can be a string or a buffer.\n\n

\n

Example:\n\n

\n
fs.appendFile('message.txt', 'data to append', function (err) {\n  if (err) throw err;\n  console.log('The "data to append" was appended to file!');\n});
\n" }, { "textRaw": "fs.appendFileSync(filename, data, [options])", "type": "method", "name": "appendFileSync", "desc": "

The synchronous version of fs.appendFile.\n\n

\n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "data" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.watchFile(filename, [options], listener)", "type": "method", "name": "watchFile", "stability": 2, "stabilityText": "Unstable. Use fs.watch instead, if possible.", "desc": "

Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.\n\n

\n

The second argument is optional. The options if provided should be an object\ncontaining two members a boolean, persistent, and interval. persistent\nindicates whether the process should continue to run as long as files are\nbeing watched. interval indicates how often the target should be polled,\nin milliseconds. The default is { persistent: true, interval: 5007 }.\n\n

\n

The listener gets two arguments the current stat object and the previous\nstat object:\n\n

\n
fs.watchFile('message.text', function (curr, prev) {\n  console.log('the current mtime is: ' + curr.mtime);\n  console.log('the previous mtime was: ' + prev.mtime);\n});
\n

These stat objects are instances of fs.Stat.\n\n

\n

If you want to be notified when the file was modified, not just accessed\nyou need to compare curr.mtime and prev.mtime.\n\n

\n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener" } ] } ] }, { "textRaw": "fs.unwatchFile(filename, [listener])", "type": "method", "name": "unwatchFile", "stability": 2, "stabilityText": "Unstable. Use fs.watch instead, if possible.", "desc": "

Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed and you\nhave effectively stopped watching filename.\n\n

\n

Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.\n\n

\n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "listener", "optional": true } ] } ] }, { "textRaw": "fs.watch(filename, [options], [listener])", "type": "method", "name": "watch", "stability": 2, "stabilityText": "Unstable.", "desc": "

Watch for changes on filename, where filename is either a file or a\ndirectory. The returned object is a fs.FSWatcher.\n\n

\n

The second argument is optional. The options if provided should be an object\ncontaining a boolean member persistent, which indicates whether the process\nshould continue to run as long as files are being watched. The default is\n{ persistent: true }.\n\n

\n

The listener callback gets two arguments (event, filename). event is either\n'rename' or 'change', and filename is the name of the file which triggered\nthe event.\n\n

\n", "miscs": [ { "textRaw": "Caveats", "name": "Caveats", "type": "misc", "desc": "

The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.\n\n

\n", "miscs": [ { "textRaw": "Availability", "name": "Availability", "type": "misc", "desc": "

This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.\n\n

\n\n

If the underlying functionality is not available for some reason, then\nfs.watch will not be able to function. For example, watching files or\ndirectories on network file systems (NFS, SMB, etc.) often doesn't work\nreliably or at all.\n\n

\n

You can still use fs.watchFile, which uses stat polling, but it is slower and\nless reliable.\n\n

\n" }, { "textRaw": "Filename Argument", "name": "Filename Argument", "type": "misc", "desc": "

Providing filename argument in the callback is not supported\non every platform (currently it's only supported on Linux and Windows). Even\non supported platforms filename is not always guaranteed to be provided.\nTherefore, don't assume that filename argument is always provided in the\ncallback, and have some fallback logic if it is null.\n\n

\n
fs.watch('somedir', function (event, filename) {\n  console.log('event is: ' + event);\n  if (filename) {\n    console.log('filename provided: ' + filename);\n  } else {\n    console.log('filename not provided');\n  }\n});
\n" } ] } ], "signatures": [ { "params": [ { "name": "filename" }, { "name": "options", "optional": true }, { "name": "listener", "optional": true } ] } ] }, { "textRaw": "fs.exists(path, callback)", "type": "method", "name": "exists", "desc": "

Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false. Example:\n\n

\n
fs.exists('/etc/passwd', function (exists) {\n  util.debug(exists ? "it's there" : "no passwd!");\n});
\n

fs.exists() is an anachronism and exists only for historical reasons.\nThere should almost never be a reason to use it in your own code.\n\n

\n

In particular, checking if a file exists before opening it is an anti-pattern\nthat leaves you vulnerable to race conditions: another process may remove the\nfile between the calls to fs.exists() and fs.open(). Just open the file\nand handle the error when it's not there.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.existsSync(path)", "type": "method", "name": "existsSync", "desc": "

Synchronous version of fs.exists.\n\n

\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.createReadStream(path, [options])", "type": "method", "name": "createReadStream", "desc": "

Returns a new ReadStream object (See Readable Stream).\n\n

\n

options is an object with the following defaults:\n\n

\n
{ flags: 'r',\n  encoding: null,\n  fd: null,\n  mode: 0666,\n  autoClose: true\n}
\n

options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart at 0. The encoding can be 'utf8', 'ascii', or 'base64'.\n\n

\n

If autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is your responsiblity to close it and make sure\nthere's no file descriptor leak. If autoClose is set to true (default\nbehavior), on error or end the file descriptor will be closed\nautomatically.\n\n

\n

An example to read the last 10 bytes of a file which is 100 bytes long:\n\n

\n
fs.createReadStream('sample.txt', {start: 90, end: 99});
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ] }, { "textRaw": "fs.createWriteStream(path, [options])", "type": "method", "name": "createWriteStream", "desc": "

Returns a new WriteStream object (See Writable Stream).\n\n

\n

options is an object with the following defaults:\n\n

\n
{ flags: 'w',\n  encoding: null,\n  mode: 0666 }
\n

options may also include a start option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags mode of r+ rather than the\ndefault mode w.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "options", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: fs.Stats", "type": "class", "name": "fs.Stats", "desc": "

Objects returned from fs.stat(), fs.lstat() and fs.fstat() and their\nsynchronous counterparts are of this type.\n\n

\n\n

For a regular file util.inspect(stats) would return a string very\nsimilar to this:\n\n

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

Please note that atime, mtime and ctime are instances\nof [Date][MDN-Date] object and to compare the values of\nthese objects you should use appropriate methods. For most\ngeneral uses [getTime()][MDN-Date-getTime] will return\nthe number of milliseconds elapsed since 1 January 1970\n00:00:00 UTC and this integer should be sufficient for\nany comparison, however there additional methods which can\nbe used for displaying fuzzy information. More details can\nbe found in the [MDN JavaScript Reference][MDN-Date] page.\n\n

\n" }, { "textRaw": "Class: fs.ReadStream", "type": "class", "name": "fs.ReadStream", "desc": "

ReadStream is a Readable Stream.\n\n

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

Emitted when the ReadStream's file is opened.\n\n\n

\n" } ] }, { "textRaw": "Class: fs.WriteStream", "type": "class", "name": "fs.WriteStream", "desc": "

WriteStream is a Writable Stream.\n\n

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

Emitted when the WriteStream's file is opened.\n\n

\n" } ], "properties": [ { "textRaw": "file.bytesWritten", "name": "bytesWritten", "desc": "

The number of bytes written so far. Does not include data that is still queued\nfor writing.\n\n

\n" } ] }, { "textRaw": "Class: fs.FSWatcher", "type": "class", "name": "fs.FSWatcher", "desc": "

Objects returned from fs.watch() are of this type.\n\n

\n", "methods": [ { "textRaw": "watcher.close()", "type": "method", "name": "close", "desc": "

Stop watching for changes on the given fs.FSWatcher.\n\n

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

Emitted when something changes in a watched directory or file.\nSee more details in fs.watch.\n\n

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

Emitted when an error occurs.\n\n

\n" } ] } ], "type": "module", "displayName": "fs" }, { "textRaw": "Path", "name": "path", "stability": 3, "stabilityText": "Stable", "desc": "

This module contains utilities for handling and transforming file\npaths. Almost all these methods perform only string transformations.\nThe file system is not consulted to check whether paths are valid.\n\n

\n

Use require('path') to use this module. The following methods are provided:\n\n

\n", "methods": [ { "textRaw": "path.normalize(p)", "type": "method", "name": "normalize", "desc": "

Normalize a string path, taking care of '..' and '.' parts.\n\n

\n

When multiple slashes are found, they're replaced by a single one;\nwhen the path contains a trailing slash, it is preserved.\nOn Windows backslashes are used.\n\n

\n

Example:\n\n

\n
path.normalize('/foo/bar//baz/asdf/quux/..')\n// returns\n'/foo/bar/baz/asdf'
\n", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.join([path1], [path2], [...])", "type": "method", "name": "join", "desc": "

Join all arguments together and normalize the resulting path.\n\n

\n

Arguments must be strings. In v0.8, non-string arguments were\nsilently ignored. In v0.10 and up, an exception is thrown.\n\n

\n

Example:\n\n

\n
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n// returns\n'/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar')\n// throws exception\nTypeError: Arguments to path.join must be strings
\n", "signatures": [ { "params": [ { "name": "path1", "optional": true }, { "name": "path2", "optional": true }, { "name": "...", "optional": true } ] } ] }, { "textRaw": "path.resolve([from ...], to)", "type": "method", "name": "resolve", "desc": "

Resolves to to an absolute path.\n\n

\n

If to isn't already absolute from arguments are prepended in right to left\norder, until an absolute path is found. If after using all from paths still\nno absolute path is found, the current working directory is used as well. The\nresulting path is normalized, and trailing slashes are removed unless the path\ngets resolved to the root directory. Non-string from arguments are ignored.\n\n

\n

Another way to think of it is as a sequence of cd commands in a shell.\n\n

\n
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
\n

Is similar to:\n\n

\n
cd foo/bar\ncd /tmp/file/\ncd ..\ncd a/../subfile\npwd
\n

The difference is that the different paths don't need to exist and may also be\nfiles.\n\n

\n

Examples:\n\n

\n
path.resolve('/foo/bar', './baz')\n// returns\n'/foo/bar/baz'\n\npath.resolve('/foo/bar', '/tmp/file/')\n// returns\n'/tmp/file'\n\npath.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')\n// if currently in /home/myself/node, it returns\n'/home/myself/node/wwwroot/static_files/gif/image.gif'
\n", "signatures": [ { "params": [ { "name": "from ...", "optional": true }, { "name": "to" } ] } ] }, { "textRaw": "path.relative(from, to)", "type": "method", "name": "relative", "desc": "

Solve the relative path from from to to.\n\n

\n

At times we have two absolute paths, and we need to derive the relative\npath from one to the other. This is actually the reverse transform of\npath.resolve, which means we see that:\n\n

\n
path.resolve(from, path.relative(from, to)) == path.resolve(to)
\n

Examples:\n\n

\n
path.relative('C:\\\\orandea\\\\test\\\\aaa', 'C:\\\\orandea\\\\impl\\\\bbb')\n// returns\n'..\\\\..\\\\impl\\\\bbb'\n\npath.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')\n// returns\n'../../impl/bbb'
\n", "signatures": [ { "params": [ { "name": "from" }, { "name": "to" } ] } ] }, { "textRaw": "path.dirname(p)", "type": "method", "name": "dirname", "desc": "

Return the directory name of a path. Similar to the Unix dirname command.\n\n

\n

Example:\n\n

\n
path.dirname('/foo/bar/baz/asdf/quux')\n// returns\n'/foo/bar/baz/asdf'
\n", "signatures": [ { "params": [ { "name": "p" } ] } ] }, { "textRaw": "path.basename(p, [ext])", "type": "method", "name": "basename", "desc": "

Return the last portion of a path. Similar to the Unix basename command.\n\n

\n

Example:\n\n

\n
path.basename('/foo/bar/baz/asdf/quux.html')\n// returns\n'quux.html'\n\npath.basename('/foo/bar/baz/asdf/quux.html', '.html')\n// returns\n'quux'
\n", "signatures": [ { "params": [ { "name": "p" }, { "name": "ext", "optional": true } ] } ] }, { "textRaw": "path.extname(p)", "type": "method", "name": "extname", "desc": "

Return the extension of the path, from the last '.' to end of string\nin the last portion of the path. If there is no '.' in the last portion\nof the path or the first character of it is '.', then it returns\nan empty string. Examples:\n\n

\n
path.extname('index.html')\n// returns\n'.html'\n\npath.extname('index.coffee.md')\n// returns\n'.md'\n\npath.extname('index.')\n// returns\n'.'\n\npath.extname('index')\n// returns\n''
\n", "signatures": [ { "params": [ { "name": "p" } ] } ] } ], "properties": [ { "textRaw": "path.sep", "name": "sep", "desc": "

The platform-specific file separator. '\\\\' or '/'.\n\n

\n

An example on *nix:\n\n

\n
'foo/bar/baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
\n

An example on Windows:\n\n

\n
'foo\\\\bar\\\\baz'.split(path.sep)\n// returns\n['foo', 'bar', 'baz']
\n" }, { "textRaw": "path.delimiter", "name": "delimiter", "desc": "

The platform-specific path delimiter, ; or ':'.\n\n

\n

An example on *nix:\n\n

\n
console.log(process.env.PATH)\n// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'\n\nprocess.env.PATH.split(path.delimiter)\n// returns\n['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
\n

An example on Windows:\n\n

\n
console.log(process.env.PATH)\n// 'C:\\Windows\\system32;C:\\Windows;C:\\Program Files\\nodejs\\'\n\nprocess.env.PATH.split(path.delimiter)\n// returns\n['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\nodejs\\']
\n" } ], "type": "module", "displayName": "Path" }, { "textRaw": "net", "name": "net", "stability": 3, "stabilityText": "Stable", "desc": "

The net module provides you with an asynchronous network wrapper. It contains\nmethods for creating both servers and clients (called streams). You can include\nthis module with require('net');\n\n

\n", "methods": [ { "textRaw": "net.createServer([options], [connectionListener])", "type": "method", "name": "createServer", "desc": "

Creates a new TCP server. The connectionListener argument is\nautomatically set as a listener for the ['connection'][] event.\n\n

\n

options is an object with the following defaults:\n\n

\n
{ allowHalfOpen: false\n}
\n

If allowHalfOpen is true, then the socket won't automatically send a FIN\npacket when the other end of the socket sends a FIN packet. The socket becomes\nnon-readable, but still writable. You should call the end() method explicitly.\nSee ['end'][] event for more information.\n\n

\n

Here is an example of an echo server which listens for connections\non port 8124:\n\n

\n
var net = require('net');\nvar server = net.createServer(function(c) { //'connection' listener\n  console.log('client connected');\n  c.on('end', function() {\n    console.log('client disconnected');\n  });\n  c.write('hello\\r\\n');\n  c.pipe(c);\n});\nserver.listen(8124, function() { //'listening' listener\n  console.log('server bound');\n});
\n

Test this by using telnet:\n\n

\n
telnet localhost 8124
\n

To listen on the socket /tmp/echo.sock the third line from the last would\njust be changed to\n\n

\n
server.listen('/tmp/echo.sock', function() { //'listening' listener
\n

Use nc to connect to a UNIX domain socket server:\n\n

\n
nc -U /tmp/echo.sock
\n", "signatures": [ { "params": [ { "name": "options", "optional": true }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.connect(options, [connectionListener])", "type": "method", "name": "connect", "desc": "

A factory method, which returns a new 'net.Socket'\nand connects to the supplied address and port.\n\n

\n

When the socket is established, the ['connect'][] event will be emitted.\n\n

\n

Has the same events as 'net.Socket'.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n\n

For UNIX domain sockets, options argument should be an object which specifies:\n\n

\n\n

Common options are:\n\n

\n\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('connected to server!');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('disconnected from server');\n});
\n

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
var client = net.connect({path: '/tmp/echo.sock'});
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] }, { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(options, [connectionListener])", "type": "method", "name": "createConnection", "desc": "

A factory method, which returns a new 'net.Socket'\nand connects to the supplied address and port.\n\n

\n

When the socket is established, the ['connect'][] event will be emitted.\n\n

\n

Has the same events as 'net.Socket'.\n\n

\n

For TCP sockets, options argument should be an object which specifies:\n\n

\n\n

For UNIX domain sockets, options argument should be an object which specifies:\n\n

\n\n

Common options are:\n\n

\n\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Here is an example of a client of echo server as described previously:\n\n

\n
var net = require('net');\nvar client = net.connect({port: 8124},\n    function() { //'connect' listener\n  console.log('connected to server!');\n  client.write('world!\\r\\n');\n});\nclient.on('data', function(data) {\n  console.log(data.toString());\n  client.end();\n});\nclient.on('end', function() {\n  console.log('disconnected from server');\n});
\n

To connect on the socket /tmp/echo.sock the second line would just be\nchanged to\n\n

\n
var client = net.connect({path: '/tmp/echo.sock'});
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "connectionListener", "optional": true } ] } ] }, { "textRaw": "net.connect(port, [host], [connectListener])", "type": "method", "name": "connect", "desc": "

Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Is a factory method which returns a new 'net.Socket'.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(port, [host], [connectListener])", "type": "method", "name": "createConnection", "desc": "

Creates a TCP connection to port on host. If host is omitted,\n'localhost' will be assumed.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

Is a factory method which returns a new 'net.Socket'.\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.connect(path, [connectListener])", "type": "method", "name": "connect", "desc": "

Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

A factory method which returns a new 'net.Socket'.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.createConnection(path, [connectListener])", "type": "method", "name": "createConnection", "desc": "

Creates unix socket connection to path.\nThe connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n

\n

A factory method which returns a new 'net.Socket'.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "net.isIP(input)", "type": "method", "name": "isIP", "desc": "

Tests if input is an IP address. Returns 0 for invalid strings,\nreturns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.\n\n\n

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv4(input)", "type": "method", "name": "isIPv4", "desc": "

Returns true if input is a version 4 IP address, otherwise returns false.\n\n\n

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] }, { "textRaw": "net.isIPv6(input)", "type": "method", "name": "isIPv6", "desc": "

Returns true if input is a version 6 IP address, otherwise returns false.\n\n

\n", "signatures": [ { "params": [ { "name": "input" } ] } ] } ], "classes": [ { "textRaw": "Class: net.Server", "type": "class", "name": "net.Server", "desc": "

This class is used to create a TCP or UNIX server.\n\n

\n", "methods": [ { "textRaw": "server.listen(port, [host], [backlog], [callback])", "type": "method", "name": "listen", "desc": "

Begin accepting connections on the specified port and host. If the\nhost is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY). A port value of zero will assign a random port.\n\n

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

\n

This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

\n

One issue some users run into is getting EADDRINUSE errors. This means that\nanother server is already running on the requested port. One way of handling this\nwould be to wait a second and then try again. This can be done with\n\n

\n
server.on('error', function (e) {\n  if (e.code == 'EADDRINUSE') {\n    console.log('Address in use, retrying...');\n    setTimeout(function () {\n      server.close();\n      server.listen(PORT, HOST);\n    }, 1000);\n  }\n});
\n

(Note: All sockets in Node set SO_REUSEADDR already)\n\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. When the server has been bound,\n['listening'][] event will be emitted. The last parameter callback\nwill be added as an listener for the ['listening'][] event.\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nthe last parameter callback will be added as an listener for the\n'listening' event.\n\n

\n" }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections and keeps existing\nconnections. This function is asynchronous, the server is finally\nclosed when all connections are ended and the server emits a 'close'\nevent. Optionally, you can pass a callback to listen for the 'close'\nevent.\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.address()", "type": "method", "name": "address", "desc": "

Returns the bound address, the address family name and port of the server\nas reported by the operating system.\nUseful to find which port was assigned when giving getting an OS-assigned address.\nReturns an object with three properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

\n

Example:\n\n

\n
var server = net.createServer(function (socket) {\n  socket.end("goodbye\\n");\n});\n\n// grab a random port.\nserver.listen(function() {\n  address = server.address();\n  console.log("opened server on %j", address);\n});
\n

Don't call server.address() until the 'listening' event has been emitted.\n\n

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

Calling unref on a server will allow the program to exit if this is the only\nactive server in the event system. If the server is already unrefd calling\nunref again will have no effect.\n\n

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

Opposite of unref, calling ref on a previously unrefd server will not\nlet the program exit if it's the only server left (the default behavior). If\nthe server is refd calling ref again will have no effect.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "server.getConnections(callback)", "type": "method", "name": "getConnections", "desc": "

Asynchronously get the number of concurrent connections on the server. Works\nwhen sockets were sent to forks.\n\n

\n

Callback should take two arguments err and count.\n\n

\n

net.Server is an [EventEmitter][] with the following events:\n\n

\n", "signatures": [ { "params": [ { "name": "callback" } ] } ] } ], "properties": [ { "textRaw": "server.maxConnections", "name": "maxConnections", "desc": "

Set this property to reject connections when the server's connection count gets\nhigh.\n\n

\n

It is not recommended to use this option once a socket has been sent to a child\nwith child_process.fork().\n\n

\n" }, { "textRaw": "server.connections", "name": "connections", "desc": "

This function is deprecated; please use [server.getConnections()][] instead.\nThe number of concurrent connections on the server.\n\n

\n

This becomes null when sending a socket to a child with\nchild_process.fork(). To poll forks and get current number of active\nconnections use asynchronous server.getConnections instead.\n\n

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

Emitted when the server has been bound after calling server.listen.\n\n

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

Emitted when a new connection is made. socket is an instance of\nnet.Socket.\n\n

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

Emitted when the server closes. Note that if connections exist, this\nevent is not emitted until all connections are ended.\n\n

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

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event. See example in discussion of server.listen.\n\n

\n" } ] }, { "textRaw": "Class: net.Socket", "type": "class", "name": "net.Socket", "desc": "

This object is an abstraction of a TCP or UNIX 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\nand passed to the user through the 'connection' event of a server.\n\n

\n", "methods": [ { "textRaw": "new net.Socket([options])", "type": "method", "name": "Socket", "desc": "

Construct a new socket object.\n\n

\n

options is an object with the following defaults:\n\n

\n
{ fd: null\n  allowHalfOpen: false,\n  readable: false,\n  writable: false\n}
\n

fd allows you to specify the existing file descriptor of socket.\nSet readable and/or writable to true to allow reads and/or writes on this\nsocket (NOTE: Works only when fd is passed).\nAbout allowHalfOpen, refer to createServer() and 'end' event.\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "socket.connect(port, [host], [connectListener])", "type": "method", "name": "connect", "desc": "

Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket.\n\n

\n

This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "host", "optional": true }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.connect(path, [connectListener])", "type": "method", "name": "connect", "desc": "

Opens the connection for a given socket. If port and host are given,\nthen the socket will be opened as a TCP socket, if host is omitted,\nlocalhost will be assumed. If a path is given, the socket will be\nopened as a unix socket to that path.\n\n

\n

Normally this method is not needed, as net.createConnection opens the\nsocket. Use this only if you are implementing a custom Socket.\n\n

\n

This function is asynchronous. When the ['connect'][] event is emitted the\nsocket is established. If there is a problem connecting, the 'connect' event\nwill not be emitted, the 'error' event will be emitted with the exception.\n\n

\n

The connectListener parameter will be added as an listener for the\n['connect'][] event.\n\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "connectListener", "optional": true } ] } ] }, { "textRaw": "socket.setEncoding([encoding])", "type": "method", "name": "setEncoding", "desc": "

Set the encoding for the socket as a Readable Stream. See\n[stream.setEncoding()][] for more information.\n\n

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.write(data, [encoding], [callback])", "type": "method", "name": "write", "desc": "

Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.\n\n

\n

Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

\n

The optional callback parameter will be executed when the data is finally\nwritten out - this may not be immediately.\n\n

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.end([data], [encoding])", "type": "method", "name": "end", "desc": "

Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.\n\n

\n

If data is specified, it is equivalent to calling\nsocket.write(data, encoding) followed by socket.end().\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "socket.destroy()", "type": "method", "name": "destroy", "desc": "

Ensures that no more I/O activity happens on this socket. Only necessary in\ncase of errors (parse error or so).\n\n

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

Pauses the reading of data. That is, 'data' events will not be emitted.\nUseful to throttle back an upload.\n\n

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

Resumes reading after a call to pause().\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.setTimeout(timeout, [callback])", "type": "method", "name": "setTimeout", "desc": "

Sets the socket to timeout after timeout milliseconds of inactivity on\nthe socket. By default net.Socket do not have a timeout.\n\n

\n

When an idle timeout is triggered the socket will receive a 'timeout'\nevent but the connection will not be severed. The user must manually end()\nor destroy() the socket.\n\n

\n

If timeout is 0, then the existing idle timeout is disabled.\n\n

\n

The optional callback parameter will be added as a one time listener for the\n'timeout' event.\n\n

\n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "socket.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

Disables the Nagle algorithm. By default TCP connections use the Nagle\nalgorithm, they buffer data before sending it off. Setting true for\nnoDelay will immediately fire off data each time socket.write() is called.\nnoDelay defaults to true.\n\n

\n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "socket.setKeepAlive([enable], [initialDelay])", "type": "method", "name": "setKeepAlive", "desc": "

Enable/disable keep-alive functionality, and optionally set the initial\ndelay before the first keepalive probe is sent on an idle socket.\nenable defaults to false.\n\n

\n

Set initialDelay (in milliseconds) to set the delay between the last\ndata packet received and the first keepalive probe. Setting 0 for\ninitialDelay will leave the value unchanged from the default\n(or previous) setting. Defaults to 0.\n\n

\n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] }, { "textRaw": "socket.address()", "type": "method", "name": "address", "desc": "

Returns the bound address, the address family name and port of the\nsocket as reported by the operating system. Returns an object with\nthree properties, e.g.\n{ port: 12346, family: 'IPv4', address: '127.0.0.1' }\n\n

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

Calling unref on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefd calling\nunref again will have no effect.\n\n

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

Opposite of unref, calling ref on a previously unrefd socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is refd calling ref again will have no effect.\n\n

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

net.Socket has the property that socket.write() always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket - the network connection\nsimply might be too slow. Node will internally queue up the data written to a\nsocket and send it out over the wire when it is possible. (Internally it is\npolling on the socket's file descriptor for being writable).\n\n

\n

The consequence of this internal buffering is that memory may grow. This\nproperty shows the number of characters currently buffered to be written.\n(Number of characters is approximately equal to the number of bytes to be\nwritten, but the buffer may contain strings, and the strings are lazily\nencoded, so the exact number of bytes is not known.)\n\n

\n

Users who experience large or growing bufferSize should attempt to\n"throttle" the data flows in their program with pause() and resume().\n\n\n

\n" }, { "textRaw": "socket.remoteAddress", "name": "remoteAddress", "desc": "

The string representation of the remote IP address. For example,\n'74.125.127.100' or '2001:4860:a005::68'.\n\n

\n" }, { "textRaw": "socket.remotePort", "name": "remotePort", "desc": "

The numeric representation of the remote port. For example,\n80 or 21.\n\n

\n" }, { "textRaw": "socket.localAddress", "name": "localAddress", "desc": "

The string representation of the local IP address the remote client is\nconnecting on. For example, if you are listening on '0.0.0.0' and the\nclient connects on '192.168.1.1', the value would be '192.168.1.1'.\n\n

\n" }, { "textRaw": "socket.localPort", "name": "localPort", "desc": "

The numeric representation of the local port. For example,\n80 or 21.\n\n

\n" }, { "textRaw": "socket.bytesRead", "name": "bytesRead", "desc": "

The amount of received bytes.\n\n

\n" }, { "textRaw": "socket.bytesWritten", "name": "bytesWritten", "desc": "

The amount of bytes sent.\n\n\n

\n

net.Socket instances are [EventEmitter][] with the following events:\n\n

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

Emitted when a socket connection is successfully established.\nSee connect().\n\n

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

Emitted when data is received. The argument data will be a Buffer or\nString. Encoding of data is set by socket.setEncoding().\n(See the [Readable Stream][] section for more information.)\n\n

\n

Note that the data will be lost if there is no listener when a Socket\nemits a 'data' event.\n\n

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

Emitted when the other end of the socket sends a FIN packet.\n\n

\n

By default (allowHalfOpen == false) the socket will destroy its file\ndescriptor once it has written out its pending write queue. However, by\nsetting allowHalfOpen == true the socket will not automatically end()\nits side allowing the user to write arbitrary amounts of data, with the\ncaveat that the user is required to end() their side now.\n\n\n

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

Emitted if the socket times out from inactivity. This is only to notify that\nthe socket has been idle. The user must manually close the connection.\n\n

\n

See also: socket.setTimeout()\n\n\n

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

Emitted when the write buffer becomes empty. Can be used to throttle uploads.\n\n

\n

See also: the return values of socket.write()\n\n

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

Emitted when an error occurs. The 'close' event will be called directly\nfollowing this event.\n\n

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

Emitted once the socket is fully closed. The argument had_error is a boolean\nwhich says if the socket was closed due to a transmission error.\n\n

\n" } ] } ], "type": "module", "displayName": "net" }, { "textRaw": "UDP / Datagram Sockets", "name": "dgram", "stability": 3, "stabilityText": "Stable", "desc": "

Datagram sockets are available through require('dgram').\n\n

\n

Important note: the behavior of dgram.Socket#bind() has changed in v0.10\nand is always asynchronous now. If you have code that looks like this:\n\n

\n
var s = dgram.createSocket('udp4');\ns.bind(1234);\ns.addMembership('224.0.0.114');
\n

You have to change it to this:\n\n

\n
var s = dgram.createSocket('udp4');\ns.bind(1234, function() {\n  s.addMembership('224.0.0.114');\n});
\n", "methods": [ { "textRaw": "dgram.createSocket(type, [callback])", "type": "method", "name": "createSocket", "signatures": [ { "return": { "textRaw": "Returns: Socket object ", "name": "return", "desc": "Socket object" }, "params": [ { "textRaw": "`type` String. Either 'udp4' or 'udp6' ", "name": "type", "desc": "String. Either 'udp4' or 'udp6'" }, { "textRaw": "`callback` Function. Attached as a listener to `message` events. Optional ", "name": "callback", "optional": true, "desc": "Function. Attached as a listener to `message` events." } ] }, { "params": [ { "name": "type" }, { "name": "callback", "optional": true } ] } ], "desc": "

Creates a datagram Socket of the specified types. Valid types are udp4\nand udp6.\n\n

\n

Takes an optional callback which is added as a listener for message events.\n\n

\n

Call socket.bind if you want to receive datagrams. socket.bind() will bind\nto the "all interfaces" address on a random port (it does the right thing for\nboth udp4 and udp6 sockets). You can then retrieve the address and port\nwith socket.address().address and socket.address().port.\n\n

\n" } ], "classes": [ { "textRaw": "Class: dgram.Socket", "type": "class", "name": "dgram.Socket", "desc": "

The dgram Socket class encapsulates the datagram functionality. It\nshould be created via dgram.createSocket(type, [callback]).\n\n

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

Emitted when a new datagram is available on a socket. msg is a Buffer and rinfo is\nan object with the sender's address information and the number of bytes in the datagram.\n\n

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

Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets\nare created.\n\n

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

Emitted when a socket is closed with close(). No new message events will be emitted\non this socket.\n\n

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

Emitted when an error occurs.\n\n

\n" } ], "methods": [ { "textRaw": "socket.send(buf, offset, length, port, address, [callback])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`buf` Buffer object. Message to be sent ", "name": "buf", "desc": "Buffer object. Message to be sent" }, { "textRaw": "`offset` Integer. Offset in the buffer where the message starts. ", "name": "offset", "desc": "Integer. Offset in the buffer where the message starts." }, { "textRaw": "`length` Integer. Number of bytes in the message. ", "name": "length", "desc": "Integer. Number of bytes in the message." }, { "textRaw": "`port` Integer. Destination port. ", "name": "port", "desc": "Integer. Destination port." }, { "textRaw": "`address` String. Destination hostname or IP address. ", "name": "address", "desc": "String. Destination hostname or IP address." }, { "textRaw": "`callback` Function. Called when the message has been sent. Optional. ", "name": "callback", "desc": "Function. Called when the message has been sent. Optional.", "optional": true } ] }, { "params": [ { "name": "buf" }, { "name": "offset" }, { "name": "length" }, { "name": "port" }, { "name": "address" }, { "name": "callback", "optional": true } ] } ], "desc": "

For UDP sockets, the destination port and address must be specified. A string\nmay be supplied for the address parameter, and it will be resolved with DNS.\n\n

\n

If the address is omitted or is an empty string, '0.0.0.0' or '::0' is used\ninstead. Depending on the network configuration, those defaults may or may not\nwork; it's best to be explicit about the destination address.\n\n

\n

If the socket has not been previously bound with a call to bind, it gets\nassigned a random port number and is bound to the "all interfaces" address\n('0.0.0.0' for udp4 sockets, '::0' for udp6 sockets.)\n\n

\n

An optional callback may be specified to detect DNS errors or for determining\nwhen it's safe to reuse the buf object. Note that DNS lookups delay the time\nto send for at least one tick. The only way to know for sure that the datagram\nhas been sent is by using a callback.\n\n

\n

Example of sending a UDP packet to a random port on localhost;\n\n

\n
var dgram = require('dgram');\nvar message = new Buffer("Some bytes");\nvar client = dgram.createSocket("udp4");\nclient.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {\n  client.close();\n});
\n

A Note about UDP datagram size\n\n

\n

The maximum size of an IPv4/v6 datagram depends on the MTU (Maximum Transmission Unit)\nand on the Payload Length field size.\n\n

\n\n

Note that it's impossible to know in advance the MTU of each link through which\na packet might travel, and that generally sending a datagram greater than\nthe (receiver) MTU won't work (the packet gets silently dropped, without\ninforming the source that the data did not reach its intended recipient).\n\n

\n" }, { "textRaw": "socket.bind(port, [address], [callback])", "type": "method", "name": "bind", "signatures": [ { "params": [ { "textRaw": "`port` Integer ", "name": "port", "desc": "Integer" }, { "textRaw": "`address` String, Optional ", "name": "address", "optional": true, "desc": "String" }, { "textRaw": "`callback` Function with no parameters, Optional. Callback when binding is done. ", "name": "callback", "desc": "Function with no parameters, Optional. Callback when binding is done.", "optional": true } ] }, { "params": [ { "name": "port" }, { "name": "address", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

For UDP sockets, listen for datagrams on a named port and optional\naddress. If address is not specified, the OS will try to listen on\nall addresses. After binding is done, a "listening" event is emitted\nand the callback(if specified) is called. Specifying both a\n"listening" event listener and callback is not harmful but not very\nuseful.\n\n

\n

A bound datagram socket keeps the node process running to receive\ndatagrams.\n\n

\n

If binding fails, an "error" event is generated. In rare case (e.g.\nbinding a closed socket), an Error may be thrown by this method.\n\n

\n

Example of a UDP server listening on port 41234:\n\n

\n
var dgram = require("dgram");\n\nvar server = dgram.createSocket("udp4");\n\nserver.on("error", function (err) {\n  console.log("server error:\\n" + err.stack);\n  server.close();\n});\n\nserver.on("message", function (msg, rinfo) {\n  console.log("server got: " + msg + " from " +\n    rinfo.address + ":" + rinfo.port);\n});\n\nserver.on("listening", function () {\n  var address = server.address();\n  console.log("server listening " +\n      address.address + ":" + address.port);\n});\n\nserver.bind(41234);\n// server listening 0.0.0.0:41234
\n" }, { "textRaw": "socket.close()", "type": "method", "name": "close", "desc": "

Close the underlying socket and stop listening for data on it.\n\n

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

Returns an object containing the address information for a socket. For UDP sockets,\nthis object will contain address , family and port.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.setBroadcast(flag)", "type": "method", "name": "setBroadcast", "signatures": [ { "params": [ { "textRaw": "`flag` Boolean ", "name": "flag", "desc": "Boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "desc": "

Sets or clears the SO_BROADCAST socket option. When this option is set, UDP packets\nmay be sent to a local interface's broadcast address.\n\n

\n" }, { "textRaw": "socket.setTTL(ttl)", "type": "method", "name": "setTTL", "signatures": [ { "params": [ { "textRaw": "`ttl` Integer ", "name": "ttl", "desc": "Integer" } ] }, { "params": [ { "name": "ttl" } ] } ], "desc": "

Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context it\nspecifies the number of IP hops that a packet is allowed to go through. Each router or\ngateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a\nrouter, it will not be forwarded. Changing TTL values is typically done for network\nprobes or when multicasting.\n\n

\n

The argument to setTTL() is a number of hops between 1 and 255. The default on most\nsystems is 64.\n\n

\n" }, { "textRaw": "socket.setMulticastTTL(ttl)", "type": "method", "name": "setMulticastTTL", "signatures": [ { "params": [ { "textRaw": "`ttl` Integer ", "name": "ttl", "desc": "Integer" } ] }, { "params": [ { "name": "ttl" } ] } ], "desc": "

Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in this\ncontext it specifies the number of IP hops that a packet is allowed to go through,\nspecifically for multicast traffic. Each router or gateway that forwards a packet\ndecrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.\n\n

\n

The argument to setMulticastTTL() is a number of hops between 0 and 255. The default on most\nsystems is 1.\n\n

\n" }, { "textRaw": "socket.setMulticastLoopback(flag)", "type": "method", "name": "setMulticastLoopback", "signatures": [ { "params": [ { "textRaw": "`flag` Boolean ", "name": "flag", "desc": "Boolean" } ] }, { "params": [ { "name": "flag" } ] } ], "desc": "

Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set, multicast\npackets will also be received on the local interface.\n\n

\n" }, { "textRaw": "socket.addMembership(multicastAddress, [multicastInterface])", "type": "method", "name": "addMembership", "signatures": [ { "params": [ { "textRaw": "`multicastAddress` String ", "name": "multicastAddress", "desc": "String" }, { "textRaw": "`multicastInterface` String, Optional ", "name": "multicastInterface", "optional": true, "desc": "String" } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "desc": "

Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket option.\n\n

\n

If multicastInterface is not specified, the OS will try to add membership to all valid\ninterfaces.\n\n

\n" }, { "textRaw": "socket.dropMembership(multicastAddress, [multicastInterface])", "type": "method", "name": "dropMembership", "signatures": [ { "params": [ { "textRaw": "`multicastAddress` String ", "name": "multicastAddress", "desc": "String" }, { "textRaw": "`multicastInterface` String, Optional ", "name": "multicastInterface", "optional": true, "desc": "String" } ] }, { "params": [ { "name": "multicastAddress" }, { "name": "multicastInterface", "optional": true } ] } ], "desc": "

Opposite of addMembership - tells the kernel to leave a multicast group with\nIP_DROP_MEMBERSHIP socket option. This is automatically called by the kernel\nwhen the socket is closed or process terminates, so most apps will never need to call\nthis.\n\n

\n

If multicastInterface is not specified, the OS will try to drop membership to all valid\ninterfaces.\n\n

\n" }, { "textRaw": "socket.unref()", "type": "method", "name": "unref", "desc": "

Calling unref on a socket will allow the program to exit if this is the only\nactive socket in the event system. If the socket is already unrefd calling\nunref again will have no effect.\n\n

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

Opposite of unref, calling ref on a previously unrefd socket will not\nlet the program exit if it's the only socket left (the default behavior). If\nthe socket is refd calling ref again will have no effect.\n\n

\n", "signatures": [ { "params": [] } ] } ] } ], "type": "module", "displayName": "dgram" }, { "textRaw": "DNS", "name": "dns", "stability": 3, "stabilityText": "Stable", "desc": "

Use require('dns') to access this module.\n\n

\n

This module contains functions that belong to two different categories:\n\n

\n

1) Functions that use the underlying operating system facilities to perform\nname resolution, and that do not necessarily do any network communication.\nThis category contains only one function: dns.lookup. Developers looking\nto perform name resolution in the same way that other applications on the same\noperating system behave should use dns.lookup.\n\n

\n

Here is an example that does a lookup of www.google.com.\n\n

\n
var dns = require('dns');\n\ndns.lookup('www.google.com', function onLookup(err, addresses, family) {\n  console.log('addresses:', addresses);\n});
\n

2) Functions that connect to an actual DNS server to perform name resolution,\nand that always use the network to perform DNS queries. This category\ncontains all functions in the dns module but dns.lookup. These functions\ndo not use the same set of configuration files than what dns.lookup uses.\nFor instance, they do not use the configuration from /etc/hosts. These\nfunctions should be used by developers who do not want to use the underlying\noperating system's facilities for name resolution, and instead want to\nalways perform DNS queries.\n\n

\n

Here is an example which resolves 'www.google.com' then reverse\nresolves the IP addresses which are returned.\n\n

\n
var dns = require('dns');\n\ndns.resolve4('www.google.com', function (err, addresses) {\n  if (err) throw err;\n\n  console.log('addresses: ' + JSON.stringify(addresses));\n\n  addresses.forEach(function (a) {\n    dns.reverse(a, function (err, domains) {\n      if (err) {\n        throw err;\n      }\n\n      console.log('reverse for ' + a + ': ' + JSON.stringify(domains));\n    });\n  });\n});
\n

There are subtle consequences in choosing one or another, please consult the\nImplementation considerations section\nfor more information.\n\n

\n", "methods": [ { "textRaw": "dns.lookup(domain, [family], callback)", "type": "method", "name": "lookup", "desc": "

Resolves a domain (e.g. 'google.com') into the first found A (IPv4) or\nAAAA (IPv6) record.\nThe family can be the integer 4 or 6. Defaults to null that indicates\nboth Ip v4 and v6 address family.\n\n

\n

The callback has arguments (err, address, family). The address argument\nis a string representation of a IP v4 or v6 address. The family argument\nis either the integer 4 or 6 and denotes the family of address (not\nnecessarily the value initially passed to lookup).\n\n

\n

On error, err is an Error object, where err.code is the error code.\nKeep in mind that err.code will be set to 'ENOENT' not only when\nthe domain does not exist but also when the lookup fails in other ways\nsuch as no available file descriptors.\n\n

\n

dns.lookup doesn't necessarily have anything to do with the DNS protocol.\nIt's only an operating system facility that can associate name with addresses,\nand vice versa.\n\n

\n

Its implementation can have subtle but important consequences on the behavior\nof any Node.js program. Please take some time to consult the Implementation\nconsiderations section before using it.\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "family", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve(domain, [rrtype], callback)", "type": "method", "name": "resolve", "desc": "

Resolves a domain (e.g. 'google.com') into an array of the record types\nspecified by rrtype. Valid rrtypes are 'A' (IPV4 addresses, default),\n'AAAA' (IPV6 addresses), 'MX' (mail exchange records), 'TXT' (text\nrecords), 'SRV' (SRV records), 'PTR' (used for reverse IP lookups),\n'NS' (name server records) and 'CNAME' (canonical name records).\n\n

\n

The callback has arguments (err, addresses). The type of each item\nin addresses is determined by the record type, and described in the\ndocumentation for the corresponding lookup methods below.\n\n

\n

On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "rrtype", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve4(domain, callback)", "type": "method", "name": "resolve4", "desc": "

The same as dns.resolve(), but only for IPv4 queries (A records).\naddresses is an array of IPv4 addresses (e.g.\n['74.125.79.104', '74.125.79.105', '74.125.79.106']).\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolve6(domain, callback)", "type": "method", "name": "resolve6", "desc": "

The same as dns.resolve4() except for IPv6 queries (an AAAA query).\n\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveMx(domain, callback)", "type": "method", "name": "resolveMx", "desc": "

The same as dns.resolve(), but only for mail exchange queries (MX records).\n\n

\n

addresses is an array of MX records, each with a priority and an exchange\nattribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveTxt(domain, callback)", "type": "method", "name": "resolveTxt", "desc": "

The same as dns.resolve(), but only for text queries (TXT records).\naddresses is an array of the text records available for domain (e.g.,\n['v=spf1 ip4:0.0.0.0 ~all']).\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveSrv(domain, callback)", "type": "method", "name": "resolveSrv", "desc": "

The same as dns.resolve(), but only for service records (SRV records).\naddresses is an array of the SRV records available for domain. Properties\nof SRV records are priority, weight, port, and name (e.g.,\n[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]).\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveNs(domain, callback)", "type": "method", "name": "resolveNs", "desc": "

The same as dns.resolve(), but only for name server records (NS records).\naddresses is an array of the name server records available for domain\n(e.g., ['ns1.example.com', 'ns2.example.com']).\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.resolveCname(domain, callback)", "type": "method", "name": "resolveCname", "desc": "

The same as dns.resolve(), but only for canonical name records (CNAME\nrecords). addresses is an array of the canonical name records available for\ndomain (e.g., ['bar.example.com']).\n\n

\n", "signatures": [ { "params": [ { "name": "domain" }, { "name": "callback" } ] } ] }, { "textRaw": "dns.reverse(ip, callback)", "type": "method", "name": "reverse", "desc": "

Reverse resolves an ip address to an array of domain names.\n\n

\n

The callback has arguments (err, domains).\n\n

\n

On error, err is an Error object, where err.code is\none of the error codes listed below.\n\n

\n", "signatures": [ { "params": [ { "name": "ip" }, { "name": "callback" } ] } ] } ], "modules": [ { "textRaw": "Error codes", "name": "error_codes", "desc": "

Each DNS query can return one of the following error codes:\n\n

\n\n", "type": "module", "displayName": "Error codes" }, { "textRaw": "Implementation considerations", "name": "implementation_considerations", "desc": "

Although dns.lookup and dns.resolve*/dns.reverse functions have the same\ngoal of associating a network name with a network address (or vice versa),\ntheir behavior is quite different. These differences can have subtle but\nsignificant consequences on the behavior of Node.js programs.\n\n

\n", "properties": [ { "textRaw": "dns.lookup", "name": "lookup", "desc": "

Under the hood, dns.lookup uses the same operating system facilities as most\nother programs. For instance, dns.lookup will almost always resolve a given\nname the same way as the ping command. On most POSIX-like operating systems,\nthe behavior of the dns.lookup function can be tweaked by changing settings\nin nsswitch.conf(5) and/or resolv.conf(5), but be careful that changing\nthese files will change the behavior of all other programs running on the same\noperating system.\n\n

\n

Though the call will be asynchronous from JavaScript's perspective, it is\nimplemented as a synchronous call to getaddrinfo(3) that runs on libuv's\nthreadpool. Because libuv's threadpool has a fixed size, it means that if for\nwhatever reason the call to getaddrinfo(3) takes a long time, other\noperations 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\ndocumentation.\n\n

\n" } ], "modules": [ { "textRaw": "dns.resolve, functions starting with dns.resolve and dns.reverse", "name": "dns.resolve,_functions_starting_with_dns.resolve_and_dns.reverse", "desc": "

These functions are implemented quite differently than dns.lookup. They do\nnot use getaddrinfo(3) and they always perform a DNS query on the network.\nThis network communication is always done asynchronously, and does not use\nlibuv's threadpool.\n\n

\n

As a result, these functions cannot have the same negative impact on other\nprocessing that happens on libuv's threadpool that dns.lookup can have.\n\n

\n

They do not use the same set of configuration files than what dns.lookup\nuses. For instance, they do not use the configuration from /etc/hosts.\n\n

\n", "type": "module", "displayName": "dns.resolve, functions starting with dns.resolve and dns.reverse" } ], "type": "module", "displayName": "Implementation considerations" } ], "type": "module", "displayName": "DNS" }, { "textRaw": "HTTP", "name": "http", "stability": 3, "stabilityText": "Stable", "desc": "

To use the HTTP server and client one must require('http').\n\n

\n

The HTTP interfaces in Node are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses--the\nuser is able to stream data.\n\n

\n

HTTP message headers are represented by an object like this:\n\n

\n
{ 'content-length': '123',\n  'content-type': 'text/plain',\n  'connection': 'keep-alive',\n  'accept': '*/*' }
\n

Keys are lowercased. Values are not modified.\n\n

\n

In order to support the full spectrum of possible HTTP applications, Node's\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.\n\n\n

\n", "properties": [ { "textRaw": "`STATUS_CODES` {Object} ", "name": "STATUS_CODES", "desc": "

A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not\nFound'.\n\n

\n" }, { "textRaw": "http.globalAgent", "name": "globalAgent", "desc": "

Global instance of Agent which is used as the default for all http client\nrequests.\n\n\n

\n" }, { "textRaw": "http.IncomingMessage", "name": "IncomingMessage", "desc": "

An IncomingMessage object is created by [http.Server][] or\n[http.ClientRequest][] and passed as the first argument to the 'request'\nand 'response' event respectively. It may be used to access response status,\nheaders and data.\n\n

\n

It implements the [Readable Stream][] interface, as well as the\nfollowing additional events, methods, and properties.\n\n

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

function () { }\n\n

\n

Indicates that the underlaying connection was closed.\nJust like 'end', this event occurs only once per response.\n\n

\n", "params": [] } ], "properties": [ { "textRaw": "message.httpVersion", "name": "httpVersion", "desc": "

In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1' or '1.0'.\n\n

\n

Also response.httpVersionMajor is the first integer and\nresponse.httpVersionMinor is the second.\n\n

\n" }, { "textRaw": "message.headers", "name": "headers", "desc": "

The request/response headers object.\n\n

\n

Read only map of header names and values. Header names are lower-cased.\nExample:\n\n

\n
// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n//   host: '127.0.0.1:8000',\n//   accept: '*/*' }\nconsole.log(request.headers);
\n" }, { "textRaw": "message.trailers", "name": "trailers", "desc": "

The request/response trailers object. Only populated after the 'end' event.\n\n

\n" }, { "textRaw": "message.method", "name": "method", "desc": "

Only valid for request obtained from [http.Server][].\n\n

\n

The request method as a string. Read only. Example:\n'GET', 'DELETE'.\n\n

\n" }, { "textRaw": "message.url", "name": "url", "desc": "

Only valid for request obtained from [http.Server][].\n\n

\n

Request URL string. This contains only the URL that is\npresent in the actual HTTP request. If the request is:\n\n

\n
GET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n
\n

Then request.url will be:\n\n

\n
'/status?name=ryan'
\n

If you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url). Example:\n\n

\n
node> require('url').parse('/status?name=ryan')\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: 'name=ryan',\n  pathname: '/status' }
\n

If you would like to extract the params from the query string,\nyou can use the require('querystring').parse function, or pass\ntrue as the second argument to require('url').parse. Example:\n\n

\n
node> require('url').parse('/status?name=ryan', true)\n{ href: '/status?name=ryan',\n  search: '?name=ryan',\n  query: { name: 'ryan' },\n  pathname: '/status' }
\n" }, { "textRaw": "message.statusCode", "name": "statusCode", "desc": "

Only valid for response obtained from http.ClientRequest.\n\n

\n

The 3-digit HTTP response status code. E.G. 404.\n\n

\n" }, { "textRaw": "message.socket", "name": "socket", "desc": "

The net.Socket object associated with the connection.\n\n

\n

With HTTPS support, use request.connection.verifyPeer() and\nrequest.connection.getPeerCertificate() to obtain the client's\nauthentication details.\n\n\n

\n" } ], "methods": [ { "textRaw": "message.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

Calls message.connection.setTimeout(msecs, callback).\n\n

\n" } ] } ], "methods": [ { "textRaw": "http.createServer([requestListener])", "type": "method", "name": "createServer", "desc": "

Returns a new web server object.\n\n

\n

The requestListener is a function which is automatically\nadded to the 'request' event.\n\n

\n", "signatures": [ { "params": [ { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "http.createClient([port], [host])", "type": "method", "name": "createClient", "desc": "

This function is deprecated; please use [http.request()][] instead.\nConstructs a new HTTP client. port and host refer to the server to be\nconnected to.\n\n

\n", "signatures": [ { "params": [ { "name": "port", "optional": true }, { "name": "host", "optional": true } ] } ] }, { "textRaw": "http.request(options, [callback])", "type": "method", "name": "request", "desc": "

Node maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with [url.parse()][].\n\n

\n

Options:\n\n

\n\n

The optional callback parameter will be added as a one time listener for\nthe ['response'][] event.\n\n

\n

http.request() returns an instance of the [http.ClientRequest][]\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.\n\n

\n

Example:\n\n

\n
var options = {\n  hostname: 'www.google.com',\n  port: 80,\n  path: '/upload',\n  method: 'POST'\n};\n\nvar req = http.request(options, function(res) {\n  console.log('STATUS: ' + res.statusCode);\n  console.log('HEADERS: ' + JSON.stringify(res.headers));\n  res.setEncoding('utf8');\n  res.on('data', function (chunk) {\n    console.log('BODY: ' + chunk);\n  });\n});\n\nreq.on('error', function(e) {\n  console.log('problem with request: ' + e.message);\n});\n\n// write data to request body\nreq.write('data\\n');\nreq.write('data\\n');\nreq.end();
\n

Note that in the example req.end() was called. With http.request() one\nmust always call req.end() to signify that you're done with the request -\neven if there is no data being written to the request body.\n\n

\n

If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object.\n\n

\n

There are a few special headers that should be noted.\n\n

\n\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "http.get(options, [callback])", "type": "method", "name": "get", "desc": "

Since most requests are GET requests without bodies, Node provides this\nconvenience method. The only difference between this method and http.request()\nis that it sets the method to GET and calls req.end() automatically.\n\n

\n

Example:\n\n

\n
http.get("http://www.google.com/index.html", function(res) {\n  console.log("Got response: " + res.statusCode);\n}).on('error', function(e) {\n  console.log("Got error: " + e.message);\n});
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: http.Server", "type": "class", "name": "http.Server", "desc": "

This is an [EventEmitter][] with the following events:\n\n

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

function (request, response) { }\n\n

\n

Emitted each time there is a request. Note that there may be multiple requests\nper connection (in the case of keep-alive connections).\n request is an instance of [http.IncomingMessage][] and response is\nan instance of [http.ServerResponse][].\n\n

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

function (socket) { }\n\n

\n

When a new TCP stream is established. socket is an object of type\n net.Socket. Usually users will not want to access this event. In\n particular, the socket will not emit readable events because of how\n the protocol parser attaches to the socket. The socket can also be\n accessed at request.connection.\n\n

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

function () { }\n\n

\n

Emitted when the server closes.\n\n

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

function (request, response) { }\n\n

\n

Emitted each time a request with an http Expect: 100-continue is received.\nIf this event isn't listened for, the server will automatically respond\nwith a 100 Continue as appropriate.\n\n

\n

Handling this event involves calling [response.writeContinue()][] if the client\nshould continue to send the request body, or generating an appropriate HTTP\nresponse (e.g., 400 Bad Request) if the client should not continue to send the\nrequest body.\n\n

\n

Note that when this event is emitted and handled, the request event will\nnot be emitted.\n\n

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

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http CONNECT method. If this event isn't\nlistened for, then clients requesting a CONNECT method will have their\nconnections closed.\n\n

\n\n

After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

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

function (request, socket, head) { }\n\n

\n

Emitted each time a client requests a http upgrade. If this event isn't\nlistened for, then clients requesting an upgrade will have their connections\nclosed.\n\n

\n\n

After this event is emitted, the request's socket will not have a data\nevent listener, meaning you will need to bind to it in order to handle data\nsent to the server on that socket.\n\n

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

function (exception, socket) { }\n\n

\n

If a client connection emits an 'error' event - it will forwarded here.\n\n

\n

socket is the net.Socket object that the error originated from.\n\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [hostname], [backlog], [callback])", "type": "method", "name": "listen", "desc": "

Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY).\n\n

\n

To listen to a unix socket, supply a filename instead of port and hostname.\n\n

\n

Backlog is the maximum length of the queue of pending connections.\nThe actual length will be determined by your OS through sysctl settings such as\ntcp_max_syn_backlog and somaxconn on linux. The default value of this\nparameter is 511 (not 512).\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(port)][].\n\n\n

\n", "signatures": [ { "params": [ { "name": "port" }, { "name": "hostname", "optional": true }, { "name": "backlog", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

Start a UNIX socket server listening for connections on the given path.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the ['listening'][] event. See also [net.Server.listen(path)][].\n\n\n

\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "signatures": [ { "params": [ { "textRaw": "`handle` {Object} ", "name": "handle", "type": "Object" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ], "desc": "

The handle object can be set to either a server or socket (anything\nwith an underlying _handle member), or a {fd: <n>} object.\n\n

\n

This will cause the server to accept connections on the specified\nhandle, but it is presumed that the file descriptor or handle has\nalready been bound to a port or domain socket.\n\n

\n

Listening on a file descriptor is not supported on Windows.\n\n

\n

This function is asynchronous. The last parameter callback will be added as\na listener for the 'listening' event.\nSee also net.Server.listen().\n\n

\n" }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

Stops the server from accepting new connections. See [net.Server.close()][].\n\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

Sets the timeout value for sockets, and emits a 'timeout' event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.\n\n

\n

If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.\n\n

\n

By default, the Server's timeout value is 2 minutes, and sockets are\ndestroyed automatically if they time out. However, if you assign a\ncallback to the Server's 'timeout' event, then you are responsible\nfor handling socket timeouts.\n\n

\n" } ], "properties": [ { "textRaw": "server.maxHeadersCount", "name": "maxHeadersCount", "desc": "

Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -\nno limit will be applied.\n\n

\n" }, { "textRaw": "`timeout` {Number} Default = 120000 (2 minutes) ", "name": "timeout", "desc": "

The number of milliseconds of inactivity before a socket is presumed\nto have timed out.\n\n

\n

Note that the socket timeout logic is set up on connection, so\nchanging this value only affects new connections to the server, not\nany existing connections.\n\n

\n

Set to 0 to disable any kind of automatic timeout behavior on incoming\nconnections.\n\n

\n", "shortDesc": "Default = 120000 (2 minutes)" } ] }, { "textRaw": "Class: http.ServerResponse", "type": "class", "name": "http.ServerResponse", "desc": "

This object is created internally by a HTTP server--not by the user. It is\npassed as the second parameter to the 'request' event.\n\n

\n

The response implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

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

function () { }\n\n

\n

Indicates that the underlying connection was terminated before\n[response.end()][] was called or able to flush.\n\n

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

function () { }\n\n

\n

Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.\n\n

\n

After this event, no more events will be emitted on the response object.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "response.writeContinue()", "type": "method", "name": "writeContinue", "desc": "

Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the ['checkContinue'][] event on Server.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "response.writeHead(statusCode, [reasonPhrase], [headers])", "type": "method", "name": "writeHead", "desc": "

Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable reasonPhrase as the second\nargument.\n\n

\n

Example:\n\n

\n
var body = 'hello world';\nresponse.writeHead(200, {\n  'Content-Length': body.length,\n  'Content-Type': 'text/plain' });
\n

This method must only be called once on a message and it must\nbe called before [response.end()][] is called.\n\n

\n

If you call [response.write()][] or [response.end()][] before calling this, the\nimplicit/mutable headers will be calculated and call this function for you.\n\n

\n

Note: that Content-Length is given in bytes not characters. The above example\nworks because the string 'hello world' contains only single byte characters.\nIf the body contains higher coded characters then Buffer.byteLength()\nshould be used to determine the number of bytes in a given encoding.\nAnd Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

\n", "signatures": [ { "params": [ { "name": "statusCode" }, { "name": "reasonPhrase", "optional": true }, { "name": "headers", "optional": true } ] } ] }, { "textRaw": "response.setTimeout(msecs, callback)", "type": "method", "name": "setTimeout", "signatures": [ { "params": [ { "textRaw": "`msecs` {Number} ", "name": "msecs", "type": "Number" }, { "textRaw": "`callback` {Function} ", "name": "callback", "type": "Function" } ] }, { "params": [ { "name": "msecs" }, { "name": "callback" } ] } ], "desc": "

Sets the Socket's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.\n\n

\n

If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If you\nassign a handler on the request, the response, or the server's\n'timeout' events, then it is your responsibility to handle timed out\nsockets.\n\n

\n" }, { "textRaw": "response.setHeader(name, value)", "type": "method", "name": "setHeader", "desc": "

Sets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere if you need to send multiple headers with the same name.\n\n

\n

Example:\n\n

\n
response.setHeader("Content-Type", "text/html");
\n

or\n\n

\n
response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);
\n", "signatures": [ { "params": [ { "name": "name" }, { "name": "value" } ] } ] }, { "textRaw": "response.getHeader(name)", "type": "method", "name": "getHeader", "desc": "

Reads out a header that's already been queued but not sent to the client. Note\nthat the name is case insensitive. This can only be called before headers get\nimplicitly flushed.\n\n

\n

Example:\n\n

\n
var contentType = response.getHeader('content-type');
\n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.removeHeader(name)", "type": "method", "name": "removeHeader", "desc": "

Removes a header that's queued for implicit sending.\n\n

\n

Example:\n\n

\n
response.removeHeader("Content-Encoding");
\n", "signatures": [ { "params": [ { "name": "name" } ] } ] }, { "textRaw": "response.write(chunk, [encoding])", "type": "method", "name": "write", "desc": "

If this method is called and [response.writeHead()][] has not been called,\nit will switch to implicit header mode and flush the implicit headers.\n\n

\n

This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.\n\n

\n

chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding is 'utf8'.\n\n

\n

Note: This is the raw HTTP body and has nothing to do with\nhigher-level multi-part body encodings that may be used.\n\n

\n

The first time response.write() is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write() is called, Node assumes you're going to be streaming\ndata, and sends that separately. That is, the response is buffered up to the\nfirst chunk of body.\n\n

\n

Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is again free.\n\n

\n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "response.addTrailers(headers)", "type": "method", "name": "addTrailers", "desc": "

This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.\n\n

\n

Trailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g., if the request was HTTP/1.0), they will\nbe silently discarded.\n\n

\n

Note that HTTP requires the Trailer header to be sent if you intend to\nemit trailers, with a list of the header fields in its value. E.g.,\n\n

\n
response.writeHead(200, { 'Content-Type': 'text/plain',\n                          'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});\nresponse.end();
\n", "signatures": [ { "params": [ { "name": "headers" } ] } ] }, { "textRaw": "response.end([data], [encoding])", "type": "method", "name": "end", "desc": "

This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each\nresponse.\n\n

\n

If data is specified, it is equivalent to calling response.write(data, encoding)\nfollowed by response.end().\n\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] } ], "properties": [ { "textRaw": "response.statusCode", "name": "statusCode", "desc": "

When using implicit headers (not calling [response.writeHead()][] explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.\n\n

\n

Example:\n\n

\n
response.statusCode = 404;
\n

After response header was sent to the client, this property indicates the\nstatus code which was sent out.\n\n

\n" }, { "textRaw": "response.headersSent", "name": "headersSent", "desc": "

Boolean (read-only). True if headers were sent, false otherwise.\n\n

\n" }, { "textRaw": "response.sendDate", "name": "sendDate", "desc": "

When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.\n\n

\n

This should only be disabled for testing; HTTP requires the Date header\nin responses.\n\n

\n" } ] }, { "textRaw": "Class: http.Agent", "type": "class", "name": "http.Agent", "desc": "

In node 0.5.3+ there is a new implementation of the HTTP Agent which is used\nfor pooling sockets used in HTTP client requests.\n\n

\n

Previously, a single agent instance helped pool for a single host+port. The\ncurrent implementation now holds sockets for any number of hosts.\n\n

\n

The current HTTP Agent also defaults client requests to using\nConnection:keep-alive. If no pending HTTP requests are waiting on a socket\nto become free the socket is closed. This means that node's pool has the\nbenefit of keep-alive when under load but still does not require developers\nto manually close the HTTP clients using keep-alive.\n\n

\n

Sockets are removed from the agent's pool when the socket emits either a\n"close" event or a special "agentRemove" event. This means that if you intend\nto keep one HTTP request open for a long time and don't want it to stay in the\npool you can do something along the lines of:\n\n

\n
http.get(options, function(res) {\n  // Do stuff\n}).on("socket", function (socket) {\n  socket.emit("agentRemove");\n});
\n

Alternatively, you could just opt out of pooling entirely using agent:false:\n\n

\n
http.get({hostname:'localhost', port:80, path:'/', agent:false}, function (res) {\n  // Do stuff\n})
\n", "properties": [ { "textRaw": "agent.maxSockets", "name": "maxSockets", "desc": "

By default set to 5. Determines how many concurrent sockets the agent can have\nopen per origin. Origin is either a 'host:port' or 'host:port:localAddress'\ncombination.\n\n

\n" }, { "textRaw": "agent.sockets", "name": "sockets", "desc": "

An object which contains arrays of sockets currently in use by the Agent. Do not\nmodify.\n\n

\n" }, { "textRaw": "agent.requests", "name": "requests", "desc": "

An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.\n\n

\n" } ] }, { "textRaw": "Class: http.ClientRequest", "type": "class", "name": "http.ClientRequest", "desc": "

This object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value), getHeader(name),\nremoveHeader(name) API. The actual header will be sent along with the first\ndata chunk or when closing the connection.\n\n

\n

To get the response, add a listener for 'response' to the request object.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of [http.IncomingMessage][].\n\n

\n

During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.\n\n

\n

If no 'response' handler is added, then the response will be\nentirely discarded. However, if you add a 'response' event handler,\nthen you must consume the data from the response object, either by\ncalling response.read() whenever there is a 'readable' event, or\nby adding a 'data' handler, or by calling the .resume() method.\nUntil the data is consumed, the 'end' event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.\n\n

\n

Note: Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n

\n

The request implements the [Writable Stream][] interface. This is an\n[EventEmitter][] with the following events:\n\n

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

function (response) { }\n\n

\n

Emitted when a response is received to this request. This event is emitted only\nonce. The response argument will be an instance of [http.IncomingMessage][].\n\n

\n

Options:\n\n

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

function (socket) { }\n\n

\n

Emitted after a socket is assigned to this request.\n\n

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

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with a CONNECT method. If this\nevent isn't being listened for, clients receiving a CONNECT method will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the connect event.\n\n

\n
var http = require('http');\nvar net = require('net');\nvar url = require('url');\n\n// Create an HTTP tunneling proxy\nvar proxy = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nproxy.on('connect', function(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, function() {\n    cltSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n                    'Proxy-agent: Node-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', function() {\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', function(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', function(chunk) {\n      console.log(chunk.toString());\n    });\n    socket.on('end', function() {\n      proxy.close();\n    });\n  });\n});
\n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "

function (response, socket, head) { }\n\n

\n

Emitted each time a server responds to a request with an upgrade. If this\nevent isn't being listened for, clients receiving an upgrade header will have\ntheir connections closed.\n\n

\n

A client server pair that show you how to listen for the upgrade event.\n\n

\n
var http = require('http');\n\n// Create an HTTP server\nvar srv = http.createServer(function (req, res) {\n  res.writeHead(200, {'Content-Type': 'text/plain'});\n  res.end('okay');\n});\nsrv.on('upgrade', function(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', function() {\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', function(res, socket, upgradeHead) {\n    console.log('got upgraded!');\n    socket.end();\n    process.exit(0);\n  });\n});
\n", "params": [] }, { "textRaw": "Event: 'continue'", "type": "event", "name": "continue", "desc": "

function () { }\n\n

\n

Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "request.write(chunk, [encoding])", "type": "method", "name": "write", "desc": "

Sends a chunk of the body. By calling this method\nmany times, the user can stream a request body to a\nserver--in that case it is suggested to use the\n['Transfer-Encoding', 'chunked'] header line when\ncreating the request.\n\n

\n

The chunk argument should be a [Buffer][] or a string.\n\n

\n

The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.\n\n\n

\n", "signatures": [ { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "request.end([data], [encoding])", "type": "method", "name": "end", "desc": "

Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.\n\n

\n

If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end().\n\n

\n", "signatures": [ { "params": [ { "name": "data", "optional": true }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "request.abort()", "type": "method", "name": "abort", "desc": "

Aborts a request. (New since v0.3.8.)\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.setTimeout(timeout, [callback])", "type": "method", "name": "setTimeout", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setTimeout()][] will be called.\n\n

\n", "signatures": [ { "params": [ { "name": "timeout" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "request.setNoDelay([noDelay])", "type": "method", "name": "setNoDelay", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setNoDelay()][] will be called.\n\n

\n", "signatures": [ { "params": [ { "name": "noDelay", "optional": true } ] } ] }, { "textRaw": "request.setSocketKeepAlive([enable], [initialDelay])", "type": "method", "name": "setSocketKeepAlive", "desc": "

Once a socket is assigned to this request and is connected\n[socket.setKeepAlive()][] will be called.\n\n\n

\n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] } ] } ], "type": "module", "displayName": "HTTP" }, { "textRaw": "HTTPS", "name": "https", "stability": 3, "stabilityText": "Stable", "desc": "

HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a\nseparate module.\n\n

\n", "classes": [ { "textRaw": "Class: https.Server", "type": "class", "name": "https.Server", "desc": "

This class is a subclass of tls.Server and emits events same as\nhttp.Server. See http.Server for more information.\n\n

\n" }, { "textRaw": "Class: https.Agent", "type": "class", "name": "https.Agent", "desc": "

An Agent object for HTTPS similar to [http.Agent][]. See [https.request()][]\nfor more information.\n\n\n

\n" } ], "methods": [ { "textRaw": "https.createServer(options, [requestListener])", "type": "method", "name": "createServer", "desc": "

Returns a new HTTPS web server object. The options is similar to\n[tls.createServer()][]. The requestListener is a function which is\nautomatically added to the 'request' event.\n\n

\n

Example:\n\n

\n
// curl -k https://localhost:8000/\nvar https = require('https');\nvar fs = require('fs');\n\nvar 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, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
\n

Or\n\n

\n
var https = require('https');\nvar fs = require('fs');\n\nvar options = {\n  pfx: fs.readFileSync('server.pfx')\n};\n\nhttps.createServer(options, function (req, res) {\n  res.writeHead(200);\n  res.end("hello world\\n");\n}).listen(8000);
\n", "methods": [ { "textRaw": "server.listen(path, [callback])", "type": "method", "name": "listen", "desc": "

See [http.listen()][] for details.\n\n

\n", "signatures": [ { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] }, { "params": [ { "name": "path" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.listen(handle, [callback])", "type": "method", "name": "listen", "desc": "

See [http.listen()][] for details.\n\n

\n", "signatures": [ { "params": [ { "name": "handle" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "server.close([callback])", "type": "method", "name": "close", "desc": "

See [http.close()][] for details.\n\n

\n", "signatures": [ { "params": [ { "name": "callback", "optional": true } ] } ] } ], "signatures": [ { "params": [ { "name": "options" }, { "name": "requestListener", "optional": true } ] } ] }, { "textRaw": "https.request(options, callback)", "type": "method", "name": "request", "desc": "

Makes a request to a secure web server.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

\n

All options from [http.request()][] are valid.\n\n

\n

Example:\n\n

\n
var 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, function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n});\nreq.end();\n\nreq.on('error', function(e) {\n  console.error(e);\n});
\n

The options argument has the following options\n\n

\n\n

The following options from [tls.connect()][] can also be specified. However, a\n[globalAgent][] silently ignores these.\n\n

\n\n

In order to specify these options, use a custom Agent.\n\n

\n

Example:\n\n

\n
var options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')\n};\noptions.agent = new https.Agent(options);\n\nvar req = https.request(options, function(res) {\n  ...\n}
\n

Or does not use an Agent.\n\n

\n

Example:\n\n

\n
var options = {\n  hostname: 'encrypted.google.com',\n  port: 443,\n  path: '/',\n  method: 'GET',\n  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),\n  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),\n  agent: false\n};\n\nvar req = https.request(options, function(res) {\n  ...\n}
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] }, { "textRaw": "https.get(options, callback)", "type": "method", "name": "get", "desc": "

Like http.get() but for HTTPS.\n\n

\n

options can be an object or a string. If options is a string, it is\nautomatically parsed with url.parse().\n\n

\n

Example:\n\n

\n
var https = require('https');\n\nhttps.get('https://encrypted.google.com/', function(res) {\n  console.log("statusCode: ", res.statusCode);\n  console.log("headers: ", res.headers);\n\n  res.on('data', function(d) {\n    process.stdout.write(d);\n  });\n\n}).on('error', function(e) {\n  console.error(e);\n});
\n", "signatures": [ { "params": [ { "name": "options" }, { "name": "callback" } ] } ] } ], "properties": [ { "textRaw": "https.globalAgent", "name": "globalAgent", "desc": "

Global instance of [https.Agent][] for all HTTPS client requests.\n\n

\n" } ], "type": "module", "displayName": "HTTPS" }, { "textRaw": "URL", "name": "url", "stability": 3, "stabilityText": "Stable", "desc": "

This module has utilities for URL resolution and parsing.\nCall require('url') to use it.\n\n

\n

Parsed URL objects have some or all of the following fields, depending on\nwhether or not they exist in the URL string. Any parts that are not in the URL\nstring will not be in the parsed object. Examples are shown for the URL\n\n

\n

'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'\n\n

\n\n

The following methods are provided by the URL module:\n\n

\n", "methods": [ { "textRaw": "url.parse(urlStr, [parseQueryString], [slashesDenoteHost])", "type": "method", "name": "parse", "desc": "

Take a URL string, and return an object.\n\n

\n

Pass true as the second argument to also parse\nthe query string using the querystring module.\nDefaults to false.\n\n

\n

Pass true as the third argument to treat //foo/bar as\n{ host: 'foo', pathname: '/bar' } rather than\n{ pathname: '//foo/bar' }. Defaults to false.\n\n

\n", "signatures": [ { "params": [ { "name": "urlStr" }, { "name": "parseQueryString", "optional": true }, { "name": "slashesDenoteHost", "optional": true } ] } ] }, { "textRaw": "url.format(urlObj)", "type": "method", "name": "format", "desc": "

Take a parsed URL object, and return a formatted URL string.\n\n

\n

Here's how the formatting process works:\n\n

\n\n", "signatures": [ { "params": [ { "name": "urlObj" } ] } ] }, { "textRaw": "url.resolve(from, to)", "type": "method", "name": "resolve", "desc": "

Take a base URL, and a href URL, and resolve them as a browser would for\nan anchor tag. Examples:\n\n

\n
url.resolve('/one/two/three', 'four')         // '/one/two/four'\nurl.resolve('http://example.com/', '/one')    // 'http://example.com/one'\nurl.resolve('http://example.com/one', '/two') // 'http://example.com/two'
\n", "signatures": [ { "params": [ { "name": "from" }, { "name": "to" } ] } ] } ], "type": "module", "displayName": "URL" }, { "textRaw": "Query String", "name": "querystring", "stability": 3, "stabilityText": "Stable", "desc": "

This module provides utilities for dealing with query strings.\nIt provides the following methods:\n\n

\n", "methods": [ { "textRaw": "querystring.stringify(obj, [sep], [eq])", "type": "method", "name": "stringify", "desc": "

Serialize an object to a query string.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

\n

Example:\n\n

\n
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })\n// returns\n'foo=bar&baz=qux&baz=quux&corge='\n\nquerystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')\n// returns\n'foo:bar;baz:qux'
\n", "signatures": [ { "params": [ { "name": "obj" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true } ] } ] }, { "textRaw": "querystring.parse(str, [sep], [eq], [options])", "type": "method", "name": "parse", "desc": "

Deserialize a query string to an object.\nOptionally override the default separator ('&') and assignment ('=')\ncharacters.\n\n

\n

Options object may contain maxKeys property (equal to 1000 by default), it'll\nbe used to limit processed keys. Set it to 0 to remove key count limitation.\n\n

\n

Example:\n\n

\n
querystring.parse('foo=bar&baz=qux&baz=quux&corge')\n// returns\n{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
\n", "signatures": [ { "params": [ { "name": "str" }, { "name": "sep", "optional": true }, { "name": "eq", "optional": true }, { "name": "options", "optional": true } ] } ] } ], "properties": [ { "textRaw": "querystring.escape", "name": "escape", "desc": "

The escape function used by querystring.stringify,\nprovided so that it could be overridden if necessary.\n\n

\n" }, { "textRaw": "querystring.unescape", "name": "unescape", "desc": "

The unescape function used by querystring.parse,\nprovided so that it could be overridden if necessary.\n\n

\n" } ], "type": "module", "displayName": "querystring" }, { "textRaw": "punycode", "name": "punycode", "stability": 2, "stabilityText": "Unstable", "desc": "

Punycode.js is bundled with Node.js v0.6.2+. Use\nrequire('punycode') to access it. (To use it with other Node.js versions,\nuse npm to install the punycode module first.)\n\n

\n", "methods": [ { "textRaw": "punycode.decode(string)", "type": "method", "name": "decode", "desc": "

Converts a Punycode string of ASCII code points to a string of Unicode code\npoints.\n\n

\n
// decode domain name parts\npunycode.decode('maana-pta'); // 'mañana'\npunycode.decode('--dqo34k'); // '☃-⌘'
\n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "punycode.encode(string)", "type": "method", "name": "encode", "desc": "

Converts a string of Unicode code points to a Punycode string of ASCII code\npoints.\n\n

\n
// encode domain name parts\npunycode.encode('mañana'); // 'maana-pta'\npunycode.encode('☃-⌘'); // '--dqo34k'
\n", "signatures": [ { "params": [ { "name": "string" } ] } ] }, { "textRaw": "punycode.toUnicode(domain)", "type": "method", "name": "toUnicode", "desc": "

Converts a Punycode string representing a domain name to Unicode. Only the\nPunycoded parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it on a string that has already been converted to Unicode.\n\n

\n
// decode domain names\npunycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'\npunycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
\n", "signatures": [ { "params": [ { "name": "domain" } ] } ] }, { "textRaw": "punycode.toASCII(domain)", "type": "method", "name": "toASCII", "desc": "

Converts a Unicode string representing a domain name to Punycode. Only the\nnon-ASCII parts of the domain name will be converted, i.e. it doesn't matter if\nyou call it with a domain that's already in ASCII.\n\n

\n
// encode domain names\npunycode.toASCII('mañana.com'); // 'xn--maana-pta.com'\npunycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
\n", "signatures": [ { "params": [ { "name": "domain" } ] } ] } ], "properties": [ { "textRaw": "punycode.ucs2", "name": "ucs2", "modules": [ { "textRaw": "punycode.ucs2.decode(string)", "name": "punycode.ucs2.decode(string)", "desc": "

Creates an array containing the decimal code points of each Unicode character\nin the string. While JavaScript uses UCS-2\ninternally, this function\nwill convert a pair of surrogate halves (each of which UCS-2 exposes as\nseparate characters) into a single code point, matching UTF-16.\n\n

\n
punycode.ucs2.decode('abc'); // [97, 98, 99]\n// surrogate pair for U+1D306 tetragram for centre:\npunycode.ucs2.decode('\\uD834\\uDF06'); // [0x1D306]
\n", "type": "module", "displayName": "punycode.ucs2.decode(string)" }, { "textRaw": "punycode.ucs2.encode(codePoints)", "name": "punycode.ucs2.encode(codepoints)", "desc": "

Creates a string based on an array of decimal code points.\n\n

\n
punycode.ucs2.encode([97, 98, 99]); // 'abc'\npunycode.ucs2.encode([0x1D306]); // '\\uD834\\uDF06'
\n", "type": "module", "displayName": "punycode.ucs2.encode(codePoints)" } ] }, { "textRaw": "punycode.version", "name": "version", "desc": "

A string representing the current Punycode.js version number.\n\n

\n" } ], "type": "module", "displayName": "punycode" }, { "textRaw": "Readline", "name": "readline", "stability": 2, "stabilityText": "Unstable", "desc": "

To use this module, do require('readline'). Readline allows reading of a\nstream (such as process.stdin) on a line-by-line basis.\n\n

\n

Note that once you've invoked this module, your node program will not\nterminate until you've closed the interface. Here's how to allow your\nprogram to gracefully exit:\n\n

\n
var readline = require('readline');\n\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});\n\nrl.question("What do you think of node.js? ", function(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", "methods": [ { "textRaw": "readline.createInterface(options)", "type": "method", "name": "createInterface", "desc": "

Creates a readline Interface instance. Accepts an "options" Object that takes\nthe following values:\n\n

\n\n

The completer function is given the current line entered by the user, and\nis supposed to return an Array with 2 entries:\n\n

\n
    \n
  1. An Array with matching entries for the completion.

    \n
  2. \n
  3. The substring that was used for the matching.

    \n
  4. \n
\n

Which ends up looking something like:\n[[substr1, substr2, ...], originalsubstring].\n\n

\n

Example:\n\n

\n
function completer(line) {\n  var completions = '.help .error .exit .quit .q'.split(' ')\n  var hits = completions.filter(function(c) { return c.indexOf(line) == 0 })\n  // show all completions if none found\n  return [hits.length ? hits : completions, line]\n}
\n

Also completer can be run in async mode if it accepts two arguments:\n\n

\n
function completer(linePartial, callback) {\n  callback(null, [['123'], linePartial]);\n}
\n

createInterface is commonly used with process.stdin and\nprocess.stdout in order to accept user input:\n\n

\n
var readline = require('readline');\nvar rl = readline.createInterface({\n  input: process.stdin,\n  output: process.stdout\n});
\n

Once you have a readline instance, you most commonly listen for the\n"line" event.\n\n

\n

If terminal is true for this instance then the output stream will get\nthe best compatibility if it defines an output.columns property, and fires\na "resize" event on the output if/when the columns ever change\n(process.stdout does this automatically when it is a TTY).\n\n

\n", "signatures": [ { "params": [ { "name": "options" } ] } ] }, { "textRaw": "readline.cursorTo(stream, x, y)", "type": "method", "name": "cursorTo", "desc": "

Move cursor to the specified position in a given TTY stream.\n\n

\n", "signatures": [ { "params": [ { "name": "stream" }, { "name": "x" }, { "name": "y" } ] } ] }, { "textRaw": "readline.moveCursor(stream, dx, dy)", "type": "method", "name": "moveCursor", "desc": "

Move cursor relative to it's current position in a given TTY stream.\n\n

\n", "signatures": [ { "params": [ { "name": "stream" }, { "name": "dx" }, { "name": "dy" } ] } ] }, { "textRaw": "readline.clearLine(stream, dir)", "type": "method", "name": "clearLine", "desc": "

Clears current line of given TTY stream in a specified direction.\ndir should have one of following values:\n\n

\n\n", "signatures": [ { "params": [ { "name": "stream" }, { "name": "dir" } ] } ] }, { "textRaw": "readline.clearScreenDown(stream)", "type": "method", "name": "clearScreenDown", "desc": "

Clears the screen from the current position of the cursor down.\n\n

\n", "signatures": [ { "params": [ { "name": "stream" } ] } ] } ], "classes": [ { "textRaw": "Class: Interface", "type": "class", "name": "Interface", "desc": "

The class that represents a readline interface with an input and output\nstream.\n\n

\n", "methods": [ { "textRaw": "rl.setPrompt(prompt, length)", "type": "method", "name": "setPrompt", "desc": "

Sets the prompt, for example when you run node on the command line, you see\n> , which is node's prompt.\n\n

\n", "signatures": [ { "params": [ { "name": "prompt" }, { "name": "length" } ] } ] }, { "textRaw": "rl.prompt([preserveCursor])", "type": "method", "name": "prompt", "desc": "

Readies readline for input from the user, putting the current setPrompt\noptions on a new line, giving the user a new spot to write. Set preserveCursor\nto true to prevent the cursor placement being reset to 0.\n\n

\n

This will also resume the input stream used with createInterface if it has\nbeen paused.\n\n

\n", "signatures": [ { "params": [ { "name": "preserveCursor", "optional": true } ] } ] }, { "textRaw": "rl.question(query, callback)", "type": "method", "name": "question", "desc": "

Prepends the prompt with query and invokes callback with the user's\nresponse. Displays the query to the user, and then invokes callback\nwith the user's response after it has been typed.\n\n

\n

This will also resume the input stream used with createInterface if\nit has been paused.\n\n

\n

Example usage:\n\n

\n
interface.question('What is your favorite food?', function(answer) {\n  console.log('Oh, so your favorite food is ' + answer);\n});
\n", "signatures": [ { "params": [ { "name": "query" }, { "name": "callback" } ] } ] }, { "textRaw": "rl.pause()", "type": "method", "name": "pause", "desc": "

Pauses the readline input stream, allowing it to be resumed later if needed.\n\n

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

Resumes the readline input stream.\n\n

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

Closes the Interface instance, relinquishing control on the input and\noutput streams. The "close" event will also be emitted.\n\n

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.write(data, [key])", "type": "method", "name": "write", "desc": "

Writes data to output stream. key is an object literal to represent a key\nsequence; available if the terminal is a TTY.\n\n

\n

This will also resume the input stream if it has been paused.\n\n

\n

Example:\n\n

\n
rl.write('Delete me!');\n// Simulate ctrl+u to delete the line written previously\nrl.write(null, {ctrl: true, name: 'u'});
\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "key", "optional": true } ] } ] } ] } ], "modules": [ { "textRaw": "Events", "name": "events", "events": [ { "textRaw": "Event: 'line'", "type": "event", "name": "line", "desc": "

function (line) {}\n\n

\n

Emitted whenever the input stream receives a \\n, usually received when the\nuser hits enter, or return. This is a good hook to listen for user input.\n\n

\n

Example of listening for line:\n\n

\n
rl.on('line', function (cmd) {\n  console.log('You just typed: '+cmd);\n});
\n", "params": [] }, { "textRaw": "Event: 'pause'", "type": "event", "name": "pause", "desc": "

function () {}\n\n

\n

Emitted whenever the input stream is paused.\n\n

\n

Also emitted whenever the input stream is not paused and receives the\nSIGCONT event. (See events SIGTSTP and SIGCONT)\n\n

\n

Example of listening for pause:\n\n

\n
rl.on('pause', function() {\n  console.log('Readline paused.');\n});
\n", "params": [] }, { "textRaw": "Event: 'resume'", "type": "event", "name": "resume", "desc": "

function () {}\n\n

\n

Emitted whenever the input stream is resumed.\n\n

\n

Example of listening for resume:\n\n

\n
rl.on('resume', function() {\n  console.log('Readline resumed.');\n});
\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "

function () {}\n\n

\n

Emitted when close() is called.\n\n

\n

Also emitted when the input stream receives its "end" event. The Interface\ninstance should be considered "finished" once this is emitted. For example, when\nthe input stream receives ^D, respectively known as EOT.\n\n

\n

This event is also called if there is no SIGINT event listener present when\nthe input stream receives a ^C, respectively known as SIGINT.\n\n

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

function () {}\n\n

\n

Emitted whenever the input stream receives a ^C, respectively known as\nSIGINT. If there is no SIGINT event listener present when the input\nstream receives a SIGINT, pause will be triggered.\n\n

\n

Example of listening for SIGINT:\n\n

\n
rl.on('SIGINT', function() {\n  rl.question('Are you sure you want to exit?', function(answer) {\n    if (answer.match(/^y(es)?$/i)) rl.pause();\n  });\n});
\n", "params": [] }, { "textRaw": "Event: 'SIGTSTP'", "type": "event", "name": "SIGTSTP", "desc": "

function () {}\n\n

\n

This does not work on Windows.\n\n

\n

Emitted whenever the input stream receives a ^Z, respectively known as\nSIGTSTP. If there is no SIGTSTP event listener present when the input\nstream receives a SIGTSTP, the program will be sent to the background.\n\n

\n

When the program is resumed with fg, the pause and SIGCONT events will be\nemitted. You can use either to resume the stream.\n\n

\n

The pause and SIGCONT events will not be triggered if the stream was paused\nbefore the program was sent to the background.\n\n

\n

Example of listening for SIGTSTP:\n\n

\n
rl.on('SIGTSTP', function() {\n  // This will override SIGTSTP and prevent the program from going to the\n  // background.\n  console.log('Caught SIGTSTP.');\n});
\n", "params": [] }, { "textRaw": "Event: 'SIGCONT'", "type": "event", "name": "SIGCONT", "desc": "

function () {}\n\n

\n

This does not work on Windows.\n\n

\n

Emitted whenever the input stream is sent to the background with ^Z,\nrespectively known as SIGTSTP, and then continued with fg(1). This event\nonly emits if the stream was not paused before sending the program to the\nbackground.\n\n

\n

Example of listening for SIGCONT:\n\n

\n
rl.on('SIGCONT', function() {\n  // `prompt` will automatically resume the stream\n  rl.prompt();\n});
\n

Example: Tiny CLI

\n

Here's an example of how to use all these together to craft a tiny command\nline interface:\n\n

\n
var readline = require('readline'),\n    rl = readline.createInterface(process.stdin, process.stdout);\n\nrl.setPrompt('OHAI> ');\nrl.prompt();\n\nrl.on('line', function(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', function() {\n  console.log('Have a great day!');\n  process.exit(0);\n});
\n", "params": [] } ], "type": "module", "displayName": "Events" } ], "type": "module", "displayName": "Readline" }, { "textRaw": "REPL", "name": "repl", "desc": "

A Read-Eval-Print-Loop (REPL) is available both as a standalone program and\neasily includable in other programs. The REPL provides a way to interactively\nrun JavaScript and see the results. It can be used for debugging, testing, or\njust trying things out.\n\n

\n

By executing node without any arguments from the command-line you will be\ndropped into the REPL. It has simplistic emacs line-editing.\n\n

\n
mjr:~$ node\nType '.help' for options.\n> a = [ 1, 2, 3];\n[ 1, 2, 3 ]\n> a.forEach(function (v) {\n...   console.log(v);\n...   });\n1\n2\n3
\n

For advanced line-editors, start node with the environmental variable\nNODE_NO_READLINE=1. This will start the main and debugger REPL in canonical\nterminal settings which will allow you to use with rlwrap.\n\n

\n

For example, you could add this to your bashrc file:\n\n

\n
alias node="env NODE_NO_READLINE=1 rlwrap node"
\n", "methods": [ { "textRaw": "repl.start(options)", "type": "method", "name": "start", "desc": "

Returns and starts a REPLServer instance. Accepts an "options" Object that\ntakes the following values:\n\n

\n\n

You can use your own eval function if it has following signature:\n\n

\n
function eval(cmd, context, filename, callback) {\n  callback(null, result);\n}
\n

Multiple REPLs may be started against the same running instance of node. Each\nwill share the same global object but will have unique I/O.\n\n

\n

Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:\n\n

\n
var net = require("net"),\n    repl = require("repl");\n\nconnections = 0;\n\nrepl.start({\n  prompt: "node via stdin> ",\n  input: process.stdin,\n  output: process.stdout\n});\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via Unix socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  })\n}).listen("/tmp/node-repl-sock");\n\nnet.createServer(function (socket) {\n  connections += 1;\n  repl.start({\n    prompt: "node via TCP socket> ",\n    input: socket,\n    output: socket\n  }).on('exit', function() {\n    socket.end();\n  });\n}).listen(5001);
\n

Running this program from the command line will start a REPL on stdin. Other\nREPL clients may connect through the Unix socket or TCP socket. telnet is useful\nfor connecting to TCP sockets, and socat can be used to connect to both Unix and\nTCP sockets.\n\n

\n

By starting a REPL from a Unix socket-based server instead of stdin, you can\nconnect to a long-running node process without restarting it.\n\n

\n

For an example of running a "full-featured" (terminal) REPL over\na net.Server and net.Socket instance, see: https://gist.github.com/2209310\n\n

\n

For an example of running a REPL instance over curl(1),\nsee: https://gist.github.com/2053342\n\n

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

function () {}\n\n

\n

Emitted when the user exits the REPL in any of the defined ways. Namely, typing\n.exit at the repl, pressing Ctrl+C twice to signal SIGINT, or pressing Ctrl+D\nto signal "end" on the input stream.\n\n

\n

Example of listening for exit:\n\n

\n
r.on('exit', function () {\n  console.log('Got "exit" event from repl!');\n  process.exit();\n});
\n", "params": [] } ], "signatures": [ { "params": [ { "name": "options" } ] } ] } ], "miscs": [ { "textRaw": "REPL Features", "name": "REPL Features", "type": "misc", "desc": "

Inside the REPL, Control+D will exit. Multi-line expressions can be input.\nTab completion is supported for both global and local variables.\n\n

\n

The special variable _ (underscore) contains the result of the last expression.\n\n

\n
> [ "a", "b", "c" ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\n4
\n

The REPL provides access to any variables in the global scope. You can expose\na variable to the REPL explicitly by assigning it to the context object\nassociated with each REPLServer. For example:\n\n

\n
// repl_test.js\nvar repl = require("repl"),\n    msg = "message";\n\nrepl.start("> ").context.m = msg;
\n

Things in the context object appear as local within the REPL:\n\n

\n
mjr:~$ node repl_test.js\n> m\n'message'
\n

There are a few special REPL commands:\n\n

\n\n

The following key combinations in the REPL have these special effects:\n\n

\n\n" } ], "type": "module", "displayName": "REPL" }, { "textRaw": "Executing JavaScript", "name": "vm", "stability": 2, "stabilityText": "Unstable. See Caveats, below.", "desc": "

You can access this module with:\n\n

\n
var vm = require('vm');
\n

JavaScript code can be compiled and run immediately or compiled, saved, and run later.\n\n

\n", "modules": [ { "textRaw": "Caveats", "name": "caveats", "desc": "

The vm module has many known issues and edge cases. If you run into\nissues or unexpected behavior, please consult the open issues on\nGitHub.\nSome of the biggest problems are described below.\n\n

\n", "modules": [ { "textRaw": "Sandboxes", "name": "sandboxes", "desc": "

The sandbox argument to vm.runInNewContext and vm.createContext,\nalong with the initSandbox argument to vm.createContext, do not\nbehave as one might normally expect and their behavior varies\nbetween different versions of Node.\n\n

\n

The key issue to be aware of is that V8 provides no way to directly\ncontrol the global object used within a context. As a result, while\nproperties of your sandbox object will be available in the context,\nany properties from the prototypes of the sandbox may not be\navailable. Furthermore, the this expression within the global scope\nof the context evaluates to the empty object ({}) instead of to\nyour sandbox.\n\n

\n

Your sandbox's properties are also not shared directly with the script.\nInstead, the properties of the sandbox are copied into the context at\nthe beginning of execution, and then after execution, the properties\nare copied back out in an attempt to propagate any changes.\n\n

\n", "type": "module", "displayName": "Sandboxes" }, { "textRaw": "Globals", "name": "globals", "desc": "

Properties of the global object, like Array and String, have\ndifferent values inside of a context. This means that common\nexpressions like [] instanceof Array or\nObject.getPrototypeOf([]) === Array.prototype may not produce\nexpected results when used inside of scripts evaluated via the vm module.\n\n

\n

Some of these problems have known workarounds listed in the issues for\nvm on GitHub. for example, Array.isArray works around\nthe example problem with Array.\n\n

\n", "type": "module", "displayName": "Globals" } ], "type": "module", "displayName": "Caveats" } ], "methods": [ { "textRaw": "vm.runInThisContext(code, [filename])", "type": "method", "name": "runInThisContext", "desc": "

vm.runInThisContext() compiles code, runs it and returns the result. Running\ncode does not have access to local scope. filename is optional, it's used only\nin stack traces.\n\n

\n

Example of using vm.runInThisContext and eval to run the same code:\n\n

\n
var localVar = 123,\n    usingscript, evaled,\n    vm = require('vm');\n\nusingscript = vm.runInThisContext('localVar = 1;',\n  'myfile.vm');\nconsole.log('localVar: ' + localVar + ', usingscript: ' +\n  usingscript);\nevaled = eval('localVar = 1;');\nconsole.log('localVar: ' + localVar + ', evaled: ' +\n  evaled);\n\n// localVar: 123, usingscript: 1\n// localVar: 1, evaled: 1
\n

vm.runInThisContext does not have access to the local scope, so localVar is unchanged.\neval does have access to the local scope, so localVar is changed.\n\n

\n

In case of syntax error in code, vm.runInThisContext emits the syntax error to stderr\nand throws an exception.\n\n\n

\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.runInNewContext(code, [sandbox], [filename])", "type": "method", "name": "runInNewContext", "desc": "

vm.runInNewContext compiles code, then runs it in sandbox and returns the\nresult. Running code does not have access to local scope. The object sandbox\nwill be used as the global object for code.\nsandbox and filename are optional, filename is only used in stack traces.\n\n

\n

Example: compile and execute code that increments a global variable and sets a new one.\nThese globals are contained in the sandbox.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 3, name: 'kitty' }
\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n

In case of syntax error in code, vm.runInNewContext emits the syntax error to stderr\nand throws an exception.\n\n

\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "sandbox", "optional": true }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.runInContext(code, context, [filename])", "type": "method", "name": "runInContext", "desc": "

vm.runInContext compiles code, then runs it in context and returns the\nresult. A (V8) context comprises a global object, together with a set of\nbuilt-in objects and functions. Running code does not have access to local scope\nand the global object held within context will be used as the global object\nfor code.\nfilename is optional, it's used only in stack traces.\n\n

\n

Example: compile and execute code in a existing context.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    initSandbox = {\n      animal: 'cat',\n      count: 2\n    },\n    context = vm.createContext(initSandbox);\n\nvm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');\nconsole.log(util.inspect(context));\n\n// { animal: 'cat', count: 3, name: 'CATT' }
\n

Note that createContext will perform a shallow clone of the supplied sandbox object in order to\ninitialize the global object of the freshly constructed context.\n\n

\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, vm.runInContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n

In case of syntax error in code, vm.runInContext emits the syntax error to stderr\nand throws an exception.\n\n

\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "context" }, { "name": "filename", "optional": true } ] } ] }, { "textRaw": "vm.createContext([initSandbox])", "type": "method", "name": "createContext", "desc": "

vm.createContext creates a new context which is suitable for use as the 2nd argument of a subsequent\ncall to vm.runInContext. A (V8) context comprises a global object together with a set of\nbuild-in objects and functions. The optional argument initSandbox will be shallow-copied\nto seed the initial contents of the global object used by the context.\n\n

\n", "signatures": [ { "params": [ { "name": "initSandbox", "optional": true } ] } ] }, { "textRaw": "vm.createScript(code, [filename])", "type": "method", "name": "createScript", "desc": "

createScript compiles code but does not run it. Instead, it returns a\nvm.Script object representing this compiled code. This script can be run\nlater many times using methods below. The returned script is not bound to any\nglobal object. It is bound before each run, just for that run. filename is\noptional, it's only used in stack traces.\n\n

\n

In case of syntax error in code, createScript prints the syntax error to stderr\nand throws an exception.\n\n\n

\n", "signatures": [ { "params": [ { "name": "code" }, { "name": "filename", "optional": true } ] } ] } ], "classes": [ { "textRaw": "Class: Script", "type": "class", "name": "Script", "desc": "

A class for running scripts. Returned by vm.createScript.\n\n

\n", "methods": [ { "textRaw": "script.runInThisContext()", "type": "method", "name": "runInThisContext", "desc": "

Similar to vm.runInThisContext but a method of a precompiled Script object.\nscript.runInThisContext runs the code of script and returns the result.\nRunning code does not have access to local scope, but does have access to the global object\n(v8: in actual context).\n\n

\n

Example of using script.runInThisContext to compile code once and run it multiple times:\n\n

\n
var vm = require('vm');\n\nglobalVar = 0;\n\nvar script = vm.createScript('globalVar += 1', 'myfile.vm');\n\nfor (var i = 0; i < 1000 ; i += 1) {\n  script.runInThisContext();\n}\n\nconsole.log(globalVar);\n\n// 1000
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "script.runInNewContext([sandbox])", "type": "method", "name": "runInNewContext", "desc": "

Similar to vm.runInNewContext a method of a precompiled Script object.\nscript.runInNewContext runs the code of script with sandbox as the global object and returns the result.\nRunning code does not have access to local scope. sandbox is optional.\n\n

\n

Example: compile code that increments a global variable and sets one, then execute this code multiple times.\nThese globals are contained in the sandbox.\n\n

\n
var util = require('util'),\n    vm = require('vm'),\n    sandbox = {\n      animal: 'cat',\n      count: 2\n    };\n\nvar script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');\n\nfor (var i = 0; i < 10 ; i += 1) {\n  script.runInNewContext(sandbox);\n}\n\nconsole.log(util.inspect(sandbox));\n\n// { animal: 'cat', count: 12, name: 'kitty' }
\n

Note that running untrusted code is a tricky business requiring great care. To prevent accidental\nglobal variable leakage, script.runInNewContext is quite useful, but safely running untrusted code\nrequires a separate process.\n\n

\n", "signatures": [ { "params": [ { "name": "sandbox", "optional": true } ] } ] } ] } ], "type": "module", "displayName": "vm" }, { "textRaw": "Child Process", "name": "child_process", "stability": 3, "stabilityText": "Stable", "desc": "

Node provides a tri-directional popen(3) facility through the\nchild_process module.\n\n

\n

It is possible to stream data through a child's stdin, stdout, and\nstderr in a fully non-blocking way. (Note that some programs use\nline-buffered I/O internally. That doesn't affect node.js but it means\ndata you send to the child process is not immediately consumed.)\n\n

\n

To create a child process use require('child_process').spawn() or\nrequire('child_process').fork(). The semantics of each are slightly\ndifferent, and explained below.\n\n

\n", "classes": [ { "textRaw": "Class: ChildProcess", "type": "class", "name": "ChildProcess", "desc": "

ChildProcess is an [EventEmitter][].\n\n

\n

Child processes always have three streams associated with them. child.stdin,\nchild.stdout, and child.stderr. These may be shared with the stdio\nstreams of the parent process, or they may be separate stream objects\nwhich can be piped to and from.\n\n

\n

The ChildProcess class is not intended to be used directly. Use the\nspawn() or fork() methods to create a Child Process instance.\n\n

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

Emitted when:\n\n

\n
    \n
  1. The process could not be spawned, or
  2. \n
  3. The process could not be killed, or
  4. \n
  5. Sending a message to the child process failed for whatever reason.
  6. \n
\n

Note that the exit-event may or may not fire after an error has occured. If\nyou are listening on both events to fire a function, remember to guard against\ncalling your function twice.\n\n

\n

See also ChildProcess#kill() and\nChildProcess#send().\n\n

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

This event is emitted after the child process ends. If the process terminated\nnormally, code is the final exit code of the process, otherwise null. If\nthe process terminated due to receipt of a signal, signal is the string name\nof the signal, otherwise null.\n\n

\n

Note that the child process stdio streams might still be open.\n\n

\n

Also, note that node establishes signal handlers for 'SIGINT' and 'SIGTERM',\nso it will not terminate due to receipt of those signals, it will exit.\n\n

\n

See waitpid(2).\n\n

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

This event is emitted when the stdio streams of a child process have all\nterminated. This is distinct from 'exit', since multiple processes\nmight share the same stdio streams.\n\n

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

This event is emitted after calling the .disconnect() method in the parent\nor in the child. After disconnecting it is no longer possible to send messages,\nand the .connected property is false.\n\n

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

Messages send by .send(message, [sendHandle]) are obtained using the\nmessage event.\n\n

\n" } ], "properties": [ { "textRaw": "`stdin` {Stream object} ", "name": "stdin", "desc": "

A Writable Stream that represents the child process's stdin.\nIf the child is waiting to read all its input, it will not continue until this\nstream has been closed via end().\n\n

\n

If the child was not spawned with stdio[0] set to 'pipe', then this will\nnot be set.\n\n

\n

child.stdin is shorthand for child.stdio[0]. Both properties will refer\nto the same object, or null.\n\n

\n" }, { "textRaw": "`stdout` {Stream object} ", "name": "stdout", "desc": "

A Readable Stream that represents the child process's stdout.\n\n

\n

If the child was not spawned with stdio[1] set to 'pipe', then this will\nnot be set.\n\n

\n

child.stdout is shorthand for child.stdio[1]. Both properties will refer\nto the same object, or null.\n\n

\n" }, { "textRaw": "`stderr` {Stream object} ", "name": "stderr", "desc": "

A Readable Stream that represents the child process's stderr.\n\n

\n

If the child was not spawned with stdio[2] set to 'pipe', then this will\nnot be set.\n\n

\n

child.stderr is shorthand for child.stdio[2]. Both properties will refer\nto the same object, or null.\n\n

\n" }, { "textRaw": "`stdio` {Array} ", "name": "stdio", "desc": "

A sparse array of pipes to the child process, corresponding with positions in\nthe stdio option to\nspawn that have been\nset to 'pipe'.\nNote that streams 0-2 are also available as ChildProcess.stdin,\nChildProcess.stdout, and ChildProcess.stderr, respectively.\n\n

\n

In the following example, only the child's fd 1 is setup as a pipe, so only\nthe parent's child.stdio[1] is a stream, all other values in the array are\nnull.\n\n

\n
child = child_process.spawn("ls", {\n    stdio: [\n      0, // use parents stdin for child\n      'pipe', // pipe child's stdout to parent\n      fs.openSync("err.out", "w") // direct child's stderr to a file\n    ]\n});\n\nassert.equal(child.stdio[0], null);\nassert.equal(child.stdio[0], child.stdin);\n\nassert(child.stdout);\nassert.equal(child.stdio[1], child.stdout);\n\nassert.equal(child.stdio[2], null);\nassert.equal(child.stdio[2], child.stderr);
\n" }, { "textRaw": "`pid` {Integer} ", "name": "pid", "desc": "

The PID of the child process.\n\n

\n

Example:\n\n

\n
var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\nconsole.log('Spawned child pid: ' + grep.pid);\ngrep.stdin.end();
\n" }, { "textRaw": "`connected` {Boolean} Set to false after `.disconnect' is called ", "name": "connected", "desc": "

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

\n", "shortDesc": "Set to false after `.disconnect' is called" } ], "methods": [ { "textRaw": "child.kill([signal])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} ", "name": "signal", "type": "String", "optional": true } ] }, { "params": [ { "name": "signal", "optional": true } ] } ], "desc": "

Send a signal to the child process. If no argument is given, the process will\nbe sent 'SIGTERM'. See signal(7) for a list of available signals.\n\n

\n
var spawn = require('child_process').spawn,\n    grep  = spawn('grep', ['ssh']);\n\ngrep.on('close', function (code, signal) {\n  console.log('child process terminated due to receipt of signal '+signal);\n});\n\n// send SIGHUP to process\ngrep.kill('SIGHUP');
\n

May emit an 'error' event when the signal cannot be delivered. Sending a\nsignal to a child process that has already exited is not an error but may\nhave unforeseen consequences: if the PID (the process ID) has been reassigned\nto another process, the signal will be delivered to that process instead.\nWhat happens next is anyone's guess.\n\n

\n

Note that while the function is called kill, the signal delivered to the\nchild process may not actually kill it. kill really just sends a signal\nto a process.\n\n

\n

See kill(2)\n\n

\n" }, { "textRaw": "child.send(message, [sendHandle])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true } ] } ], "desc": "

When using child_process.fork() you can write to the child using\nchild.send(message, [sendHandle]) and messages are received by\na 'message' event on the child.\n\n

\n

For example:\n\n

\n
var cp = require('child_process');\n\nvar n = cp.fork(__dirname + '/sub.js');\n\nn.on('message', function(m) {\n  console.log('PARENT got message:', m);\n});\n\nn.send({ hello: 'world' });
\n

And then the child script, 'sub.js' might look like this:\n\n

\n
process.on('message', function(m) {\n  console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
\n

In the child the process object will have a send() method, and process\nwill emit objects each time it receives a message on its channel.\n\n

\n

Please note that the send() method on both the parent and child are\nsynchronous - sending large chunks of data is not advised (pipes can be used\ninstead, see\nchild_process.spawn).\n\n

\n

There is a special case when sending a {cmd: 'NODE_foo'} message. All messages\ncontaining a NODE_ prefix in its cmd property will not be emitted in\nthe message event, since they are internal messages used by node core.\nMessages containing the prefix are emitted in the internalMessage event, you\nshould by all means avoid using this feature, it is subject to change without notice.\n\n

\n

The sendHandle option to child.send() is for sending a TCP server or\nsocket object to another process. The child will receive the object as its\nsecond argument to the message event.\n\n

\n

Emits an 'error' event if the message cannot be sent, for example because\nthe child process has already exited.\n\n

\n

Example: sending server object

\n

Here is an example of sending a server:\n\n

\n
var child = require('child_process').fork('child.js');\n\n// Open up the server object and send the handle.\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n  socket.end('handled by parent');\n});\nserver.listen(1337, function() {\n  child.send('server', server);\n});
\n

And the child would the receive the server object as:\n\n

\n
process.on('message', function(m, server) {\n  if (m === 'server') {\n    server.on('connection', function (socket) {\n      socket.end('handled by child');\n    });\n  }\n});
\n

Note that the server is now shared between the parent and child, this means\nthat some connections will be handled by the parent and some by the child.\n\n

\n

For dgram servers the workflow is exactly the same. Here you listen on\na message event instead of connection and use server.bind instead of\nserver.listen. (Currently only supported on UNIX platforms.)\n\n

\n

Example: sending socket object

\n

Here is an example of sending a socket. It will spawn two children and handle\nconnections with the remote address 74.125.127.100 as VIP by sending the\nsocket to a "special" child process. Other sockets will go to a "normal" process.\n\n

\n
var normal = require('child_process').fork('child.js', ['normal']);\nvar special = require('child_process').fork('child.js', ['special']);\n\n// Open up the server and send sockets to child\nvar server = require('net').createServer();\nserver.on('connection', function (socket) {\n\n  // if this is a VIP\n  if (socket.remoteAddress === '74.125.127.100') {\n    special.send('socket', socket);\n    return;\n  }\n  // just the usual dudes\n  normal.send('socket', socket);\n});\nserver.listen(1337);
\n

The child.js could look like this:\n\n

\n
process.on('message', function(m, socket) {\n  if (m === 'socket') {\n    socket.end('You were handled as a ' + process.argv[2] + ' person');\n  }\n});
\n

Note that once a single socket has been sent to a child the parent can no\nlonger keep track of when the socket is destroyed. To indicate this condition\nthe .connections property becomes null.\nIt is also recommended not to use .maxConnections in this condition.\n\n

\n" }, { "textRaw": "child.disconnect()", "type": "method", "name": "disconnect", "desc": "

Close 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 .connected flag will be set to false in both the parent and\nchild, and it is no longer possible to send messages.\n\n

\n

The 'disconnect' event will be emitted when there are no messages in the process\nof being received, most likely immediately.\n\n

\n

Note that you can also call process.disconnect() in the child process when the\nchild process has any open IPC channels with the parent (i.e fork()).\n\n

\n", "signatures": [ { "params": [] } ] } ] } ], "methods": [ { "textRaw": "child_process.spawn(command, [args], [options])", "type": "method", "name": "spawn", "signatures": [ { "return": { "textRaw": "return: {ChildProcess object} ", "name": "return", "type": "ChildProcess 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": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`stdio` {Array|String} Child's stdio configuration. (See [below](#child_process_options_stdio)) ", "name": "stdio", "type": "Array|String", "desc": "Child's stdio configuration. (See [below](#child_process_options_stdio))" }, { "textRaw": "`customFds` {Array} **Deprecated** File descriptors for the child to use for stdio. (See [below](#child_process_options_customFds)) ", "name": "customFds", "type": "Array", "desc": "**Deprecated** File descriptors for the child to use for stdio. (See [below](#child_process_options_customFds))" }, { "textRaw": "`detached` {Boolean} The child will be a process group leader. (See [below](#child_process_options_detached)) ", "name": "detached", "type": "Boolean", "desc": "The child will be a process group leader. (See [below](#child_process_options_detached))" }, { "textRaw": "`uid` {Number} Sets the user identity of the process. (See setuid(2).) ", "name": "uid", "type": "Number", "desc": "Sets the user identity of the process. (See setuid(2).)" }, { "textRaw": "`gid` {Number} Sets the group identity of the process. (See setgid(2).) ", "name": "gid", "type": "Number", "desc": "Sets the group identity of the process. (See setgid(2).)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "command" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

Launches a new process with the given command, with command line arguments in args.\nIf omitted, args defaults to an empty Array.\n\n

\n

The third argument is used to specify additional options, which defaults to:\n\n

\n
{ cwd: undefined,\n  env: process.env\n}
\n

Use cwd to specify the working directory from which the process is spawned.\nIf not given, the default is to inherit the current working directory.\n\n

\n

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

\n

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

\n
var spawn = require('child_process').spawn,\n    ls    = spawn('ls', ['-lh', '/usr']);\n\nls.stdout.on('data', function (data) {\n  console.log('stdout: ' + data);\n});\n\nls.stderr.on('data', function (data) {\n  console.log('stderr: ' + data);\n});\n\nls.on('close', function (code) {\n  console.log('child process exited with code ' + code);\n});
\n

Example: A very elaborate way to run 'ps ax | grep ssh'\n\n

\n
var spawn = require('child_process').spawn,\n    ps    = spawn('ps', ['ax']),\n    grep  = spawn('grep', ['ssh']);\n\nps.stdout.on('data', function (data) {\n  grep.stdin.write(data);\n});\n\nps.stderr.on('data', function (data) {\n  console.log('ps stderr: ' + data);\n});\n\nps.on('close', function (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', function (data) {\n  console.log('' + data);\n});\n\ngrep.stderr.on('data', function (data) {\n  console.log('grep stderr: ' + data);\n});\n\ngrep.on('close', function (code) {\n  if (code !== 0) {\n    console.log('grep process exited with code ' + code);\n  }\n});
\n", "properties": [ { "textRaw": "options.stdio", "name": "stdio", "desc": "

As a shorthand, the stdio argument may also be one of the following\nstrings:\n\n

\n\n

Otherwise, the 'stdio' option to child_process.spawn() is an array where each\nindex corresponds to a fd in the child. The value is one of the following:\n\n

\n
    \n
  1. 'pipe' - Create a pipe between the child process and the parent process.\nThe parent end of the pipe is exposed to the parent as a property on the\nchild_process object as ChildProcess.stdio[fd]. Pipes created for\nfds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout\nand ChildProcess.stderr, respectively.
  2. \n
  3. 'ipc' - Create an IPC channel for passing messages/file descriptors\nbetween parent and child. A ChildProcess may have at most one IPC stdio\nfile descriptor. Setting this option enables the ChildProcess.send() method.\nIf the child writes JSON messages to this file descriptor, then this will\ntrigger ChildProcess.on('message'). If the child is a Node.js program, then\nthe presence of an IPC channel will enable process.send() and\nprocess.on('message').
  4. \n
  5. 'ignore' - Do not set this file descriptor in the child. Note that Node\nwill always open fd 0 - 2 for the processes it spawns. When any of these is\nignored node will open /dev/null and attach it to the child's fd.
  6. \n
  7. Stream object - Share a readable or writable stream that refers to a tty,\nfile, socket, or a pipe with the child process. The stream's underlying\nfile descriptor is duplicated in the child process to the fd that \ncorresponds to the index in the stdio array. Note that the stream must\nhave an underlying descriptor (file streams do not until the 'open'\nevent has occurred).
  8. \n
  9. Positive integer - The integer value is interpreted as a file descriptor \nthat is is currently open in the parent process. It is shared with the child\nprocess, similar to how Stream objects can be shared.
  10. \n
  11. null, undefined - Use default value. For stdio fds 0, 1 and 2 (in other\nwords, stdin, stdout, and stderr) a pipe is created. For fd 3 and up, the\ndefault is 'ignore'.
  12. \n
\n

Example:\n\n

\n
var 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 present a\n// startd-style interface.\nspawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
\n" }, { "textRaw": "options.detached", "name": "detached", "desc": "

If the detached option is set, the child process will be made the leader of a\nnew process group. This makes it possible for the child to continue running \nafter the parent exits.\n\n

\n

By default, the parent will wait for the detached child to exit. To prevent\nthe parent from waiting for a given child, use the child.unref() method,\nand the parent's event loop will not include the child in its reference count.\n\n

\n

Example of detaching a long-running process and redirecting its output to a\nfile:\n\n

\n
 var fs = require('fs'),\n     spawn = require('child_process').spawn,\n     out = fs.openSync('./out.log', 'a'),\n     err = fs.openSync('./out.log', 'a');\n\n var child = spawn('prg', [], {\n   detached: true,\n   stdio: [ 'ignore', out, err ]\n });\n\n child.unref();
\n

When using the detached option to start a long-running process, the process\nwill not stay running in the background unless it is provided with a stdio\nconfiguration that is not connected to the parent. If the parent's stdio is\ninherited, the child will remain attached to the controlling terminal.\n\n

\n" }, { "textRaw": "options.customFds", "name": "customFds", "desc": "

There is a deprecated option called customFds which allows one to specify\nspecific file descriptors for the stdio of the child process. This API was\nnot portable to all platforms and therefore removed.\nWith customFds it was possible to hook up the new process' [stdin, stdout,\nstderr] to existing streams; -1 meant that a new stream should be created.\nUse at your own risk.\n\n

\n

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

\n" } ] }, { "textRaw": "child_process.exec(command, [options], callback)", "type": "method", "name": "exec", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`command` {String} The command to run, with space-separated arguments ", "name": "command", "type": "String", "desc": "The command to run, with space-separated arguments" }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} (Default: `200*1024`) ", "name": "maxBuffer", "default": "200*1024", "type": "Number" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" } ], "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` {Buffer} ", "name": "stdout", "type": "Buffer" }, { "textRaw": "`stderr` {Buffer} ", "name": "stderr", "type": "Buffer" } ], "name": "callback", "type": "Function", "desc": "called with the output when process terminates" } ] }, { "params": [ { "name": "command" }, { "name": "options", "optional": true }, { "name": "callback" } ] } ], "desc": "

Runs a command in a shell and buffers the output.\n\n

\n
var exec = require('child_process').exec,\n    child;\n\nchild = exec('cat *.js bad_file | wc -l',\n  function (error, stdout, stderr) {\n    console.log('stdout: ' + stdout);\n    console.log('stderr: ' + stderr);\n    if (error !== null) {\n      console.log('exec error: ' + error);\n    }\n});
\n

The callback gets the arguments (error, stdout, stderr). On success, error\nwill be null. On error, error will be an instance of Error and error.code\nwill be the exit code of the child process, and error.signal will be set to the\nsignal that terminated the process.\n\n

\n

There is a second optional argument to specify several options. The\ndefault options are\n\n

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

If timeout is greater than 0, then it will kill the child process\nif it runs longer than timeout milliseconds. The child process is killed with\nkillSignal (default: 'SIGTERM'). maxBuffer specifies the largest\namount of data allowed on stdout or stderr - if this value is exceeded then\nthe child process is killed.\n\n\n

\n" }, { "textRaw": "child_process.execFile(file, [args], [options], [callback])", "type": "method", "name": "execFile", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`file` {String} The filename of the program to run ", "name": "file", "type": "String", "desc": "The filename of the program to run" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`encoding` {String} (Default: 'utf8') ", "name": "encoding", "default": "utf8", "type": "String" }, { "textRaw": "`timeout` {Number} (Default: 0) ", "name": "timeout", "default": "0", "type": "Number" }, { "textRaw": "`maxBuffer` {Number} (Default: 200\\*1024) ", "name": "maxBuffer", "default": "200\\*1024", "type": "Number" }, { "textRaw": "`killSignal` {String} (Default: 'SIGTERM') ", "name": "killSignal", "default": "SIGTERM", "type": "String" } ], "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` {Buffer} ", "name": "stdout", "type": "Buffer" }, { "textRaw": "`stderr` {Buffer} ", "name": "stderr", "type": "Buffer" } ], "name": "callback", "type": "Function", "desc": "called with the output when process terminates", "optional": true } ] }, { "params": [ { "name": "file" }, { "name": "args", "optional": true }, { "name": "options", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "

This is similar to child_process.exec() except it does not execute a\nsubshell but rather the specified file directly. This makes it slightly\nleaner than child_process.exec. It has the same options.\n\n\n

\n" }, { "textRaw": "child_process.fork(modulePath, [args], [options])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "Return: ChildProcess object ", "name": "return", "desc": "ChildProcess object" }, "params": [ { "textRaw": "`modulePath` {String} The module to run in the child ", "name": "modulePath", "type": "String", "desc": "The module to run in the child" }, { "textRaw": "`args` {Array} List of string arguments ", "name": "args", "type": "Array", "desc": "List of string arguments", "optional": true }, { "textRaw": "`options` {Object} ", "options": [ { "textRaw": "`cwd` {String} Current working directory of the child process ", "name": "cwd", "type": "String", "desc": "Current working directory of the child process" }, { "textRaw": "`env` {Object} Environment key-value pairs ", "name": "env", "type": "Object", "desc": "Environment key-value pairs" }, { "textRaw": "`execPath` {String} Executable used to create the child process ", "name": "execPath", "type": "String", "desc": "Executable used to create the child process" }, { "textRaw": "`execArgv` {Array} List of string arguments passed to the executable (Default: `process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "List of string arguments passed to the executable" }, { "textRaw": "`silent` {Boolean} If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for `spawn()`'s `stdio` for more details (default is false) ", "name": "silent", "type": "Boolean", "desc": "If true, stdin, stdout, and stderr of the child will be piped to the parent, otherwise they will be inherited from the parent, see the \"pipe\" and \"inherit\" options for `spawn()`'s `stdio` for more details (default is false)" } ], "name": "options", "type": "Object", "optional": true } ] }, { "params": [ { "name": "modulePath" }, { "name": "args", "optional": true }, { "name": "options", "optional": true } ] } ], "desc": "

This is a special case of the spawn() functionality for spawning Node\nprocesses. In addition to having all the methods in a normal ChildProcess\ninstance, the returned object has a communication channel built-in. See\nchild.send(message, [sendHandle]) for details.\n\n

\n

These child Nodes are still whole new instances of V8. Assume at least 30ms\nstartup and 10mb memory for each new Node. That is, you cannot create many\nthousands of them.\n\n

\n

The execPath property in the options object allows for a process to be\ncreated for the child rather than the current node executable. This should be\ndone with care and by default will talk over the fd represented an\nenvironmental variable NODE_CHANNEL_FD on the child process. The input and\noutput on this fd is expected to be line delimited JSON objects.\n\n

\n" } ], "type": "module", "displayName": "Child Process" }, { "textRaw": "Assert", "name": "assert", "stability": 5, "stabilityText": "Locked", "desc": "

This module is used for writing unit tests for your applications, you can\naccess it with require('assert').\n\n

\n", "methods": [ { "textRaw": "assert.fail(actual, expected, message, operator)", "type": "method", "name": "fail", "desc": "

Throws an exception that displays the values for actual and expected separated by the provided operator.\n\n

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

Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);\n\n

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

Tests shallow, coercive equality with the equal comparison operator ( == ).\n\n

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

Tests shallow, coercive non-equality with the not equal comparison operator ( != ).\n\n

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

Tests for deep equality.\n\n

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

Tests for any deep inequality.\n\n

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

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

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

Tests strict non-equality, as determined by the strict not equal operator ( !== )\n\n

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

Expects block to throw an error. error can be constructor, RegExp or\nvalidation function.\n\n

\n

Validate instanceof using constructor:\n\n

\n
assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  Error\n);
\n

Validate error message using RegExp:\n\n

\n
assert.throws(\n  function() {\n    throw new Error("Wrong value");\n  },\n  /value/\n);
\n

Custom error validation:\n\n

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

Expects block not to throw an error, see assert.throws for details.\n\n

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

Tests if value is not a false value, throws if it is a true value. Useful when\ntesting the first argument, error in callbacks.\n\n

\n", "signatures": [ { "params": [ { "name": "value" } ] } ] } ], "type": "module", "displayName": "Assert" }, { "textRaw": "TTY", "name": "tty", "stability": 2, "stabilityText": "Unstable", "desc": "

The tty module houses the tty.ReadStream and tty.WriteStream classes. In\nmost cases, you will not need to use this module directly.\n\n

\n

When node detects that it is being run inside a TTY context, then process.stdin\nwill be a tty.ReadStream instance and process.stdout will be\na tty.WriteStream instance. The preferred way to check if node is being run in\na TTY context is to check process.stdout.isTTY:\n\n

\n
$ node -p -e "Boolean(process.stdout.isTTY)"\ntrue\n$ node -p -e "Boolean(process.stdout.isTTY)" | cat\nfalse
\n", "methods": [ { "textRaw": "tty.isatty(fd)", "type": "method", "name": "isatty", "desc": "

Returns true or false depending on if the fd is associated with a\nterminal.\n\n\n

\n", "signatures": [ { "params": [ { "name": "fd" } ] } ] }, { "textRaw": "tty.setRawMode(mode)", "type": "method", "name": "setRawMode", "desc": "

Deprecated. Use tty.ReadStream#setRawMode()\n(i.e. process.stdin.setRawMode()) instead.\n\n\n

\n", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ], "classes": [ { "textRaw": "Class: ReadStream", "type": "class", "name": "ReadStream", "desc": "

A net.Socket subclass that represents the readable portion of a tty. In normal\ncircumstances, process.stdin will be the only tty.ReadStream instance in any\nnode program (only when isatty(0) is true).\n\n

\n", "properties": [ { "textRaw": "rs.isRaw", "name": "isRaw", "desc": "

A Boolean that is initialized to false. It represents the current "raw" state\nof the tty.ReadStream instance.\n\n

\n" } ], "methods": [ { "textRaw": "rs.setRawMode(mode)", "type": "method", "name": "setRawMode", "desc": "

mode should be true or false. This sets the properties of the\ntty.ReadStream to act either as a raw device or default. isRaw will be set\nto the resulting mode.\n\n\n

\n", "signatures": [ { "params": [ { "name": "mode" } ] } ] } ] }, { "textRaw": "Class: WriteStream", "type": "class", "name": "WriteStream", "desc": "

A net.Socket subclass that represents the writable portion of a tty. In normal\ncircumstances, process.stdout will be the only tty.WriteStream instance\never created (and only when isatty(1) is true).\n\n

\n", "properties": [ { "textRaw": "ws.columns", "name": "columns", "desc": "

A Number that gives the number of columns the TTY currently has. This property\ngets updated on "resize" events.\n\n

\n" }, { "textRaw": "ws.rows", "name": "rows", "desc": "

A Number that gives the number of rows the TTY currently has. This property\ngets updated on "resize" events.\n\n

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

function () {}\n\n

\n

Emitted by refreshSize() when either of the columns or rows properties\nhas changed.\n\n

\n
process.stdout.on('resize', function() {\n  console.log('screen size has changed!');\n  console.log(process.stdout.columns + 'x' + process.stdout.rows);\n});
\n", "params": [] } ] } ], "type": "module", "displayName": "TTY" }, { "textRaw": "Zlib", "name": "zlib", "stability": 3, "stabilityText": "Stable", "desc": "

You can access this module with:\n\n

\n
var zlib = require('zlib');
\n

This provides bindings to Gzip/Gunzip, Deflate/Inflate, and\nDeflateRaw/InflateRaw classes. Each class takes the same options, and\nis a readable/writable Stream.\n\n

\n

Examples

\n

Compressing or decompressing a file can be done by piping an\nfs.ReadStream into a zlib stream, then into an fs.WriteStream.\n\n

\n
var gzip = zlib.createGzip();\nvar fs = require('fs');\nvar inp = fs.createReadStream('input.txt');\nvar out = fs.createWriteStream('input.txt.gz');\n\ninp.pipe(gzip).pipe(out);
\n

Compressing or decompressing data in one step can be done by using\nthe convenience methods.\n\n

\n
var input = '.................................';\nzlib.deflate(input, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString('base64'));\n  }\n});\n\nvar buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');\nzlib.unzip(buffer, function(err, buffer) {\n  if (!err) {\n    console.log(buffer.toString());\n  }\n});
\n

To use this module in an HTTP client or server, use the\naccept-encoding\non requests, and the\ncontent-encoding\nheader on responses.\n\n

\n

Note: these examples are drastically simplified to show\nthe basic concept. Zlib encoding can be expensive, and the results\nought to be cached. See Memory Usage Tuning\nbelow for more information on the speed/memory/compression\ntradeoffs involved in zlib usage.\n\n

\n
// client request example\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nvar request = http.get({ host: 'izs.me',\n                         path: '/',\n                         port: 80,\n                         headers: { 'accept-encoding': 'gzip,deflate' } });\nrequest.on('response', function(response) {\n  var output = fs.createWriteStream('izs.me_index.html');\n\n  switch (response.headers['content-encoding']) {\n    // or, just use zlib.createUnzip() to handle both cases\n    case 'gzip':\n      response.pipe(zlib.createGunzip()).pipe(output);\n      break;\n    case 'deflate':\n      response.pipe(zlib.createInflate()).pipe(output);\n      break;\n    default:\n      response.pipe(output);\n      break;\n  }\n});\n\n// server example\n// Running a gzip operation on every request is quite expensive.\n// It would be much more efficient to cache the compressed buffer.\nvar zlib = require('zlib');\nvar http = require('http');\nvar fs = require('fs');\nhttp.createServer(function(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", "methods": [ { "textRaw": "zlib.createGzip([options])", "type": "method", "name": "createGzip", "desc": "

Returns a new Gzip object with an\noptions.\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGunzip([options])", "type": "method", "name": "createGunzip", "desc": "

Returns a new Gunzip object with an\noptions.\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflate([options])", "type": "method", "name": "createDeflate", "desc": "

Returns a new Deflate object with an\noptions.\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflate([options])", "type": "method", "name": "createInflate", "desc": "

Returns a new Inflate object with an\noptions.\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflateRaw([options])", "type": "method", "name": "createDeflateRaw", "desc": "

Returns a new DeflateRaw object with an\noptions.\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflateRaw([options])", "type": "method", "name": "createInflateRaw", "desc": "

Returns a new InflateRaw object with an\noptions.\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createUnzip([options])", "type": "method", "name": "createUnzip", "desc": "

Returns a new Unzip object with an\noptions.\n\n\n

\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.deflate(buf, callback)", "type": "method", "name": "deflate", "desc": "

Compress a string with Deflate.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.deflateRaw(buf, callback)", "type": "method", "name": "deflateRaw", "desc": "

Compress a string with DeflateRaw.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gzip(buf, callback)", "type": "method", "name": "gzip", "desc": "

Compress a string with Gzip.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.gunzip(buf, callback)", "type": "method", "name": "gunzip", "desc": "

Decompress a raw Buffer with Gunzip.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflate(buf, callback)", "type": "method", "name": "inflate", "desc": "

Decompress a raw Buffer with Inflate.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.inflateRaw(buf, callback)", "type": "method", "name": "inflateRaw", "desc": "

Decompress a raw Buffer with InflateRaw.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] }, { "textRaw": "zlib.unzip(buf, callback)", "type": "method", "name": "unzip", "desc": "

Decompress a raw Buffer with Unzip.\n\n

\n", "signatures": [ { "params": [ { "name": "buf" }, { "name": "callback" } ] } ] } ], "classes": [ { "textRaw": "Class: zlib.Zlib", "type": "class", "name": "zlib.Zlib", "desc": "

Not exported by the zlib module. It is documented here because it is the base\nclass of the compressor/decompressor classes.\n\n

\n", "methods": [ { "textRaw": "zlib.flush(callback)", "type": "method", "name": "flush", "desc": "

Flush pending data. Don't call this frivolously, premature flushes negatively\nimpact the effectiveness of the compression algorithm.\n\n

\n", "signatures": [ { "params": [ { "name": "callback" } ] } ] }, { "textRaw": "zlib.reset()", "type": "method", "name": "reset", "desc": "

Reset the compressor/decompressor to factory defaults. Only applicable to\nthe inflate and deflate algorithms.\n\n

\n", "signatures": [ { "params": [] } ] } ] }, { "textRaw": "Class: zlib.Gzip", "type": "class", "name": "zlib.Gzip", "desc": "

Compress data using gzip.\n\n

\n" }, { "textRaw": "Class: zlib.Gunzip", "type": "class", "name": "zlib.Gunzip", "desc": "

Decompress a gzip stream.\n\n

\n" }, { "textRaw": "Class: zlib.Deflate", "type": "class", "name": "zlib.Deflate", "desc": "

Compress data using deflate.\n\n

\n" }, { "textRaw": "Class: zlib.Inflate", "type": "class", "name": "zlib.Inflate", "desc": "

Decompress a deflate stream.\n\n

\n" }, { "textRaw": "Class: zlib.DeflateRaw", "type": "class", "name": "zlib.DeflateRaw", "desc": "

Compress data using deflate, and do not append a zlib header.\n\n

\n" }, { "textRaw": "Class: zlib.InflateRaw", "type": "class", "name": "zlib.InflateRaw", "desc": "

Decompress a raw deflate stream.\n\n

\n" }, { "textRaw": "Class: zlib.Unzip", "type": "class", "name": "zlib.Unzip", "desc": "

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting\nthe header.\n\n

\n" } ], "miscs": [ { "textRaw": "Convenience Methods", "name": "Convenience Methods", "type": "misc", "desc": "

All of these take a string or buffer as the first argument, and call the\nsupplied callback with callback(error, result). The\ncompression/decompression engine is created using the default settings\nin all convenience methods. To supply different options, use the\nzlib classes directly.\n\n

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

Each class takes an options object. All options are optional. (The\nconvenience methods use the default settings for all options.)\n\n

\n

Note that some options are only relevant when compressing, and are\nignored by the decompression classes.\n\n

\n\n

See the description of deflateInit2 and inflateInit2 at\n

\n

http://zlib.net/manual.html#Advanced for more information on these.\n\n

\n" }, { "textRaw": "Memory Usage Tuning", "name": "Memory Usage Tuning", "type": "misc", "desc": "

From zlib/zconf.h, modified to node's usage:\n\n

\n

The memory requirements for deflate are (in bytes):\n\n

\n
(1 << (windowBits+2)) +  (1 << (memLevel+9))
\n

that is: 128K for windowBits=15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.\n\n

\n

For example, if you want to reduce\nthe default memory requirements from 256K to 128K, set the options to:\n\n

\n
{ windowBits: 14, memLevel: 7 }
\n

Of course this will generally degrade compression (there's no free lunch).\n\n

\n

The memory requirements for inflate are (in bytes)\n\n

\n
1 << windowBits
\n

that is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.\n\n

\n

This is in addition to a single internal output slab buffer of size\nchunkSize, which defaults to 16K.\n\n

\n

The speed of zlib compression is affected most dramatically by the\nlevel setting. A higher level will result in better compression, but\nwill take longer to complete. A lower level will result in less\ncompression, but will be much faster.\n\n

\n

In general, greater memory usage options will mean that node has to make\nfewer calls to zlib, since it'll be able to process more data in a\nsingle write operation. So, this is another factor that affects the\nspeed, at the cost of memory usage.\n\n

\n" }, { "textRaw": "Constants", "name": "Constants", "type": "misc", "desc": "

All of the constants defined in zlib.h are also defined on\nrequire('zlib').\nIn the normal course of operations, you will not need to ever set any of\nthese. They are documented here so that their presence is not\nsurprising. This section is taken almost directly from the zlib\ndocumentation. See\n

\n

http://zlib.net/manual.html#Constants for more details.\n\n

\n

Allowed flush values.\n\n

\n\n

Return codes for the compression/decompression functions. Negative\nvalues are errors, positive values are used for special but normal\nevents.\n\n

\n\n

Compression levels.\n\n

\n\n

Compression strategy.\n\n

\n\n

Possible values of the data_type field.\n\n

\n\n

The deflate compression method (the only one supported in this version).\n\n

\n\n

For initializing zalloc, zfree, opaque.\n\n

\n\n" } ], "type": "module", "displayName": "Zlib" }, { "textRaw": "os", "name": "os", "stability": 4, "stabilityText": "API Frozen", "desc": "

Provides a few basic operating-system related utility functions.\n\n

\n

Use require('os') to access this module.\n\n

\n", "methods": [ { "textRaw": "os.tmpdir()", "type": "method", "name": "tmpdir", "desc": "

Returns the operating system's default directory for temp files.\n\n

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

Returns the endianness of the CPU. Possible values are "BE" or "LE".\n\n

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

Returns the hostname of the operating system.\n\n

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

Returns the operating system name.\n\n

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

Returns the operating system platform.\n\n

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

Returns the operating system CPU architecture.\n\n

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

Returns the operating system release.\n\n

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

Returns the system uptime in seconds.\n\n

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

Returns an array containing the 1, 5, and 15 minute load averages.\n\n

\n

The load average is a measure of system activity, calculated by the operating\nsystem and expressed as a fractional number. As a rule of thumb, the load\naverage should ideally be less than the number of logical CPUs in the system.\n\n

\n

The load average is a very UNIX-y concept; there is no real equivalent on\nWindows platforms. That is why this function always returns [0, 0, 0] on\nWindows.\n\n

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

Returns the total amount of system memory in bytes.\n\n

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

Returns the amount of free system memory in bytes.\n\n

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

Returns an array of objects containing information about each CPU/core\ninstalled: model, speed (in MHz), and times (an object containing the number of\nmilliseconds the CPU/core spent in: user, nice, sys, idle, and irq).\n\n

\n

Example inspection of os.cpus:\n\n

\n
[ { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 252020,\n       nice: 0,\n       sys: 30340,\n       idle: 1070356870,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 306960,\n       nice: 0,\n       sys: 26980,\n       idle: 1071569080,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 248450,\n       nice: 0,\n       sys: 21750,\n       idle: 1070919370,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 256880,\n       nice: 0,\n       sys: 19430,\n       idle: 1070905480,\n       irq: 20 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 511580,\n       nice: 20,\n       sys: 40900,\n       idle: 1070842510,\n       irq: 0 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 291660,\n       nice: 0,\n       sys: 34360,\n       idle: 1070888000,\n       irq: 10 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 308260,\n       nice: 0,\n       sys: 55410,\n       idle: 1071129970,\n       irq: 880 } },\n  { model: 'Intel(R) Core(TM) i7 CPU         860  @ 2.80GHz',\n    speed: 2926,\n    times:\n     { user: 266450,\n       nice: 1480,\n       sys: 34920,\n       idle: 1072572010,\n       irq: 30 } } ]
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "os.networkInterfaces()", "type": "method", "name": "networkInterfaces", "desc": "

Get a list of network interfaces:\n\n

\n
{ lo0: \n   [ { address: '::1', family: 'IPv6', internal: true },\n     { address: 'fe80::1', family: 'IPv6', internal: true },\n     { address: '127.0.0.1', family: 'IPv4', internal: true } ],\n  en1: \n   [ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',\n       internal: false },\n     { address: '10.0.1.123', family: 'IPv4', internal: false } ],\n  vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],\n  vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],\n  ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }
\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "os.EOL", "name": "EOL", "desc": "

A constant defining the appropriate End-of-line marker for the operating system.\n\n

\n" } ], "type": "module", "displayName": "os" }, { "textRaw": "Cluster", "name": "cluster", "stability": 1, "stabilityText": "Experimental", "desc": "

A single instance of Node runs in a single thread. To take advantage of\nmulti-core systems the user will sometimes want to launch a cluster of Node\nprocesses to handle the load.\n\n

\n

The cluster module allows you to easily create child processes that\nall share server ports.\n\n

\n
var cluster = require('cluster');\nvar http = require('http');\nvar numCPUs = require('os').cpus().length;\n\nif (cluster.isMaster) {\n  // Fork workers.\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  cluster.on('exit', function(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 its a HTTP server\n  http.createServer(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n  }).listen(8000);\n}
\n

Running node will now share port 8000 between the workers:\n\n

\n
% NODE_DEBUG=cluster node server.js\n23521,Master Worker 23524 online\n23521,Master Worker 23526 online\n23521,Master Worker 23523 online\n23521,Master Worker 23528 online
\n

This feature was introduced recently, and may change in future versions.\nPlease try it out and provide feedback.\n\n

\n

Also note that, on Windows, it is not yet possible to set up a named pipe\nserver in a worker.\n\n

\n", "miscs": [ { "textRaw": "How It Works", "name": "How It Works", "type": "misc", "desc": "

The worker processes are spawned using the child_process.fork method,\nso that they can communicate with the parent via IPC and pass server\nhandles back and forth.\n\n

\n

When you call server.listen(...) in a worker, it serializes the\narguments and passes the request to the master process. If the master\nprocess already has a listening server matching the worker's\nrequirements, then it passes the handle to the worker. If it does not\nalready have a listening server matching that requirement, then it will\ncreate one, and pass the handle to the worker.\n\n

\n

This causes potentially surprising behavior in three edge cases:\n\n

\n
    \n
  1. server.listen({fd: 7}) Because the message is passed to the master,\nfile descriptor 7 in the parent will be listened on, and the\nhandle passed to the worker, rather than listening to the worker's\nidea of what the number 7 file descriptor references.
  2. \n
  3. server.listen(handle) Listening on handles explicitly will cause\nthe worker to use the supplied handle, rather than talk to the master\nprocess. If the worker already has the handle, then it's presumed\nthat you know what you are doing.
  4. \n
  5. server.listen(0) Normally, this will cause servers to listen on a\nrandom port. However, in a cluster, each worker will receive the\nsame "random" port each time they do listen(0). In essence, the\nport is random the first time, but predictable thereafter. If you\nwant to listen on a unique port, generate a port number based on the\ncluster worker ID.
  6. \n
\n

When multiple processes are all accept()ing on the same underlying\nresource, the operating system load-balances across them very\nefficiently. There is no routing logic in Node.js, or in your program,\nand no shared state between the workers. Therefore, it is important to\ndesign your program such that it does not rely too heavily on in-memory\ndata objects for things like sessions and login.\n\n

\n

Because workers are all separate processes, they can be killed or\nre-spawned depending on your program's needs, without affecting other\nworkers. As long as there are some workers still alive, the server will\ncontinue to accept connections. Node does not automatically manage the\nnumber of workers for you, however. It is your responsibility to manage\nthe worker pool for your application's needs.\n\n

\n" } ], "properties": [ { "textRaw": "`settings` {Object} ", "name": "settings", "options": [ { "textRaw": "`execArgv` {Array} list of string arguments passed to the node executable. (Default=`process.execArgv`) ", "name": "execArgv", "default": "process.execArgv", "type": "Array", "desc": "list of string arguments passed to the node executable." }, { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." } ], "desc": "

After calling .setupMaster() (or .fork()) this settings object will contain\nthe settings, including the default values.\n\n

\n

It is effectively frozen after being set, because .setupMaster() can\nonly be called once.\n\n

\n

This object is not supposed to be changed or set manually, by you.\n\n

\n" }, { "textRaw": "`isMaster` {Boolean} ", "name": "isMaster", "desc": "

True if the process is a master. This is determined\nby the process.env.NODE_UNIQUE_ID. If process.env.NODE_UNIQUE_ID is\nundefined, then isMaster is true.\n\n

\n" }, { "textRaw": "`isWorker` {Boolean} ", "name": "isWorker", "desc": "

True if the process is not a master (it is the negation of cluster.isMaster).\n\n

\n" }, { "textRaw": "`worker` {Object} ", "name": "worker", "desc": "

A reference to the current worker object. Not available in the master process.\n\n

\n
var cluster = require('cluster');\n\nif (cluster.isMaster) {\n  console.log('I am master');\n  cluster.fork();\n  cluster.fork();\n} else if (cluster.isWorker) {\n  console.log('I am worker #' + cluster.worker.id);\n}
\n" }, { "textRaw": "`workers` {Object} ", "name": "workers", "desc": "

A hash that stores the active worker objects, keyed by id field. Makes it\neasy to loop through all the workers. It is only available in the master\nprocess.\n\n

\n

A worker is removed from cluster.workers just before the 'disconnect' or\n'exit' event is emitted.\n\n

\n
// Go through all workers\nfunction eachWorker(callback) {\n  for (var id in cluster.workers) {\n    callback(cluster.workers[id]);\n  }\n}\neachWorker(function(worker) {\n  worker.send('big announcement to all workers');\n});
\n

Should you wish to reference a worker over a communication channel, using\nthe worker's unique id is the easiest way to find the worker.\n\n

\n
socket.on('data', function(id) {\n  var worker = cluster.workers[id];\n});
\n" } ], "events": [ { "textRaw": "Event: 'fork'", "type": "event", "name": "fork", "params": [], "desc": "

When a new worker is forked the cluster module will emit a 'fork' event.\nThis can be used to log worker activity, and create your own timeout.\n\n

\n
var timeouts = [];\nfunction errorMsg() {\n  console.error("Something must be wrong with the connection ...");\n}\n\ncluster.on('fork', function(worker) {\n  timeouts[worker.id] = setTimeout(errorMsg, 2000);\n});\ncluster.on('listening', function(worker, address) {\n  clearTimeout(timeouts[worker.id]);\n});\ncluster.on('exit', function(worker, code, signal) {\n  clearTimeout(timeouts[worker.id]);\n  errorMsg();\n});
\n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "params": [], "desc": "

After forking a new worker, the worker should respond with an online message.\nWhen the master receives an online message it will emit this event.\nThe difference between 'fork' and 'online' is that fork is emitted when the\nmaster forks a worker, and 'online' is emitted when the worker is running.\n\n

\n
cluster.on('online', function(worker) {\n  console.log("Yay, the worker responded after it was forked");\n});
\n" }, { "textRaw": "Event: 'listening'", "type": "event", "name": "listening", "params": [], "desc": "

After calling listen() from a worker, when the 'listening' event is emitted on\nthe server, a listening event will also be emitted on cluster in the master.\n\n

\n

The event handler is executed with two arguments, the worker contains the worker\nobject and the address object contains the following connection properties:\naddress, port and addressType. This is very useful if the worker is listening\non more than one address.\n\n

\n
cluster.on('listening', function(worker, address) {\n  console.log("A worker is now connected to " + address.address + ":" + address.port);\n});
\n

The addressType is one of:\n\n

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

Emitted after the worker IPC channel has disconnected. This can occur when a\nworker exits gracefully, is killed, or is disconnected manually (such as with\nworker.disconnect()).\n\n

\n

There may be a delay between the disconnect and exit events. These events\ncan be used to detect if the process is stuck in a cleanup or if there are\nlong-living connections.\n\n

\n
cluster.on('disconnect', function(worker) {\n  console.log('The worker #' + worker.id + ' has disconnected');\n});
\n" }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

When any of the workers die the cluster module will emit the 'exit' event.\n\n

\n

This can be used to restart the worker by calling .fork() again.\n\n

\n
cluster.on('exit', function(worker, code, signal) {\n  console.log('worker %d died (%s). restarting...',\n    worker.process.pid, signal || code);\n  cluster.fork();\n});
\n

See child_process event: 'exit'.\n\n

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

Emitted the first time that .setupMaster() is called.\n\n

\n", "params": [] } ], "methods": [ { "textRaw": "cluster.setupMaster([settings])", "type": "method", "name": "setupMaster", "signatures": [ { "params": [ { "textRaw": "`settings` {Object} ", "options": [ { "textRaw": "`exec` {String} file path to worker file. (Default=`process.argv[1]`) ", "name": "exec", "default": "process.argv[1]", "type": "String", "desc": "file path to worker file." }, { "textRaw": "`args` {Array} string arguments passed to worker. (Default=`process.argv.slice(2)`) ", "name": "args", "default": "process.argv.slice(2)", "type": "Array", "desc": "string arguments passed to worker." }, { "textRaw": "`silent` {Boolean} whether or not to send output to parent's stdio. (Default=`false`) ", "name": "silent", "default": "false", "type": "Boolean", "desc": "whether or not to send output to parent's stdio." } ], "name": "settings", "type": "Object", "optional": true } ] }, { "params": [ { "name": "settings", "optional": true } ] } ], "desc": "

setupMaster is used to change the default 'fork' behavior. Once called,\nthe settings will be present in cluster.settings.\n\n

\n

Note that:\n\n

\n\n

Example:\n\n

\n
var cluster = require("cluster");\ncluster.setupMaster({\n  exec : "worker.js",\n  args : ["--use", "https"],\n  silent : true\n});\ncluster.fork();
\n

This can only be called from the master process.\n\n

\n" }, { "textRaw": "cluster.fork([env])", "type": "method", "name": "fork", "signatures": [ { "return": { "textRaw": "return {Worker object} ", "name": "return", "type": "Worker object" }, "params": [ { "textRaw": "`env` {Object} Key/value pairs to add to worker process environment. ", "name": "env", "type": "Object", "desc": "Key/value pairs to add to worker process environment.", "optional": true } ] }, { "params": [ { "name": "env", "optional": true } ] } ], "desc": "

Spawn a new worker process.\n\n

\n

This can only be called from the master process.\n\n

\n" }, { "textRaw": "cluster.disconnect([callback])", "type": "method", "name": "disconnect", "signatures": [ { "params": [ { "textRaw": "`callback` {Function} called when all workers are disconnected and handles are closed ", "name": "callback", "type": "Function", "desc": "called when all workers are disconnected and handles are closed", "optional": true } ] }, { "params": [ { "name": "callback", "optional": true } ] } ], "desc": "

Calls .disconnect() on each worker in cluster.workers.\n\n

\n

When they are disconnected all internal handles will be closed, allowing the\nmaster process to die gracefully if no other event is waiting.\n\n

\n

The method takes an optional callback argument which will be called when finished.\n\n

\n

This can only be called from the master process.\n\n

\n" } ], "classes": [ { "textRaw": "Class: Worker", "type": "class", "name": "Worker", "desc": "

A Worker object contains all public information and method about a worker.\nIn the master it can be obtained using cluster.workers. In a worker\nit can be obtained using cluster.worker.\n\n

\n", "properties": [ { "textRaw": "`id` {String} ", "name": "id", "desc": "

Each new worker is given its own unique id, this id is stored in the\nid.\n\n

\n

While a worker is alive, this is the key that indexes it in\ncluster.workers\n\n

\n" }, { "textRaw": "`process` {ChildProcess object} ", "name": "process", "desc": "

All workers are created using child_process.fork(), the returned object\nfrom this function is stored as .process. In a worker, the global process\nis stored.\n\n

\n

See: Child Process module\n\n

\n

Note that workers will call process.exit(0) if the 'disconnect' event occurs\non process and .suicide is not true. This protects against accidental\ndisconnection.\n\n

\n" }, { "textRaw": "`suicide` {Boolean} ", "name": "suicide", "desc": "

Set by calling .kill() or .disconnect(), until then it is undefined.\n\n

\n

The boolean worker.suicide lets you distinguish between voluntary and accidental\nexit, the master may choose not to respawn a worker based on this value.\n\n

\n
cluster.on('exit', function(worker, code, signal) {\n  if (worker.suicide === true) {\n    console.log('Oh, it was just suicide\\' – no need to worry').\n  }\n});\n\n// kill worker\nworker.kill();
\n" } ], "methods": [ { "textRaw": "worker.send(message, [sendHandle])", "type": "method", "name": "send", "signatures": [ { "params": [ { "textRaw": "`message` {Object} ", "name": "message", "type": "Object" }, { "textRaw": "`sendHandle` {Handle object} ", "name": "sendHandle", "type": "Handle object", "optional": true } ] }, { "params": [ { "name": "message" }, { "name": "sendHandle", "optional": true } ] } ], "desc": "

This function is equal to the send methods provided by\nchild_process.fork(). In the master you should use this function to\nsend a message to a specific worker.\n\n

\n

In a worker you can also use process.send(message), it is the same function.\n\n

\n

This example will echo back all messages from the master:\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  worker.send('hi there');\n\n} else if (cluster.isWorker) {\n  process.on('message', function(msg) {\n    process.send(msg);\n  });\n}
\n" }, { "textRaw": "worker.kill([signal='SIGTERM'])", "type": "method", "name": "kill", "signatures": [ { "params": [ { "textRaw": "`signal` {String} Name of the kill signal to send to the worker process. ", "name": "signal", "type": "String", "desc": "Name of the kill signal to send to the worker process.", "optional": true, "default": "'SIGTERM'" } ] }, { "params": [ { "name": "signal", "optional": true, "default": "'SIGTERM'" } ] } ], "desc": "

This function will kill the worker. In the master, it does this by disconnecting\nthe worker.process, and once disconnected, killing with signal. In the\nworker, it does it by disconnecting the channel, and then exiting with code 0.\n\n

\n

Causes .suicide to be set.\n\n

\n

This method is aliased as worker.destroy() for backwards compatibility.\n\n

\n

Note that in a worker, process.kill() exists, but it is not this function,\nit is kill.\n\n

\n" }, { "textRaw": "worker.disconnect()", "type": "method", "name": "disconnect", "desc": "

In a worker, this function will close all servers, wait for the 'close' event on\nthose servers, and then disconnect the IPC channel.\n\n

\n

In the master, an internal message is sent to the worker causing it to call\n.disconnect() on itself.\n\n

\n

Causes .suicide to be set.\n\n

\n

Note that after a server is closed, it will no longer accept new connections,\nbut connections may be accepted by any other listening worker. Existing\nconnections will be allowed to close as usual. When no more connections exist,\nsee server.close(), the IPC channel to the worker\nwill close allowing it to die gracefully.\n\n

\n

The above applies only to server connections, client connections are not\nautomatically closed by workers, and disconnect does not wait for them to close\nbefore exiting.\n\n

\n

Note that in a worker, process.disconnect exists, but it is not this function,\nit is disconnect.\n\n

\n

Because long living server connections may block workers from disconnecting, it\nmay be useful to send a message, so application specific actions may be taken to\nclose them. It also may be useful to implement a timeout, killing a worker if\nthe disconnect event has not been emitted after some time.\n\n

\n
if (cluster.isMaster) {\n  var worker = cluster.fork();\n  var timeout;\n\n  worker.on('listening', function(address) {\n    worker.send('shutdown');\n    worker.disconnect();\n    timeout = setTimeout(function() {\n      worker.kill();\n    }, 2000);\n  });\n\n  worker.on('disconnect', function() {\n    clearTimeout(timeout);\n  });\n\n} else if (cluster.isWorker) {\n  var net = require('net');\n  var server = net.createServer(function(socket) {\n    // connections never end\n  });\n\n  server.listen(8000);\n\n  process.on('message', function(msg) {\n    if(msg === 'shutdown') {\n      // initiate graceful close of any connections to server\n    }\n  });\n}
\n", "signatures": [ { "params": [] } ] } ], "events": [ { "textRaw": "Event: 'message'", "type": "event", "name": "message", "params": [], "desc": "

This event is the same as the one provided by child_process.fork().\n\n

\n

In a worker you can also use process.on('message').\n\n

\n

As an example, here is a cluster that keeps count of the number of requests\nin the master process using the message system:\n\n

\n
var cluster = require('cluster');\nvar http = require('http');\n\nif (cluster.isMaster) {\n\n  // Keep track of http requests\n  var numReqs = 0;\n  setInterval(function() {\n    console.log("numReqs =", numReqs);\n  }, 1000);\n\n  // Count requestes\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  var numCPUs = require('os').cpus().length;\n  for (var i = 0; i < numCPUs; i++) {\n    cluster.fork();\n  }\n\n  Object.keys(cluster.workers).forEach(function(id) {\n    cluster.workers[id].on('message', messageHandler);\n  });\n\n} else {\n\n  // Worker processes have a http server.\n  http.Server(function(req, res) {\n    res.writeHead(200);\n    res.end("hello world\\n");\n\n    // notify master about the request\n    process.send({ cmd: 'notifyRequest' });\n  }).listen(8000);\n}
\n" }, { "textRaw": "Event: 'online'", "type": "event", "name": "online", "desc": "

Similar to the cluster.on('online') event, but specific to this worker.\n\n

\n
cluster.fork().on('online', function() {\n  // Worker is online\n});
\n

It is not emitted in the worker.\n\n

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

Similar to the cluster.on('listening') event, but specific to this worker.\n\n

\n
cluster.fork().on('listening', function(address) {\n  // Worker is listening\n});
\n

It is not emitted in the worker.\n\n

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

Similar to the cluster.on('disconnect') event, but specfic to this worker.\n\n

\n
cluster.fork().on('disconnect', function() {\n  // Worker has disconnected\n});
\n", "params": [] }, { "textRaw": "Event: 'exit'", "type": "event", "name": "exit", "params": [], "desc": "

Similar to the cluster.on('exit') event, but specific to this worker.\n\n

\n
var worker = cluster.fork();\nworker.on('exit', function(code, signal) {\n  if( signal ) {\n    console.log("worker was killed by signal: "+signal);\n  } else if( code !== 0 ) {\n    console.log("worker exited with error code: "+code);\n  } else {\n    console.log("worker success!");\n  }\n});
\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "desc": "

This event is the same as the one provided by child_process.fork().\n\n

\n

In a worker you can also use process.on('error').\n\n

\n", "params": [] } ] } ], "type": "module", "displayName": "Cluster" } ], "stability": 3, "stabilityText": "Stable" }