{ "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
\nWhere appropriate, property types, method arguments, and the arguments\nprovided to event handlers are detailed in a list underneath the topic\nheading.\n\n
\nEvery .html
document has a corresponding .json
document presenting\nthe same information in a structured manner. This feature is\nexperimental, and added for the benefit of IDEs and other utilities that\nwish to do programmatic things with the documentation.\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
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
\nThe notices look like this:\n\n
\nStability: 1 Experimental
\nThe stability indices are as follows:\n\n
\nEvery HTML file in the markdown has a corresponding JSON file with the\nsame data.\n\n
\nThis 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
\nvar 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/');
\nTo run the server, put the code into a file called example.js
and execute\nit with the node program\n\n
> node example.js\nServer running at http://127.0.0.1:8124/
\nAll 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
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 stdio section.\n\n
\n" }, { "textRaw": "Buffer", "name": "Buffer", "type": "global", "desc": "Used to handle binary data. See the buffer section.\n\n
\n" }, { "textRaw": "clearInterval(t)", "type": "global", "name": "clearInterval", "desc": "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
\n", "methods": [ { "textRaw": "console.log()", "type": "method", "name": "log", "desc": "Prints to stdout with newline. This function can take multiple arguments in a\nprintf()
-like way. Example:\n\n
console.log('count: %d', count);
\nIf formatting elements are not found in the first string then util.inspect
\nis used on each argument.\nSee util.format() for more information.\n\n
Same as console.log
.\n\n
Same as console.log
but prints to stderr.\n\n
Same as console.log
but prints to stderr.\n\n
Uses util.inspect
on obj
and prints resulting string to stderr.\n\n
Mark a time.\n\n\n
\n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "desc": "Finish timer, record output. Example\n\n
\nconsole.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n ;\n}\nconsole.timeEnd('100-elements');
\n",
"signatures": [
{
"params": [
{
"name": "label"
}
]
}
]
},
{
"textRaw": "console.trace()",
"type": "method",
"name": "trace",
"desc": "Print a stack trace to stderr of the current position.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "console.assert()", "type": "method", "name": "assert", "desc": "Same as assert.ok()
.\n\n\n
The process
object is a global object and can be accessed from anywhere.\nIt is an instance of EventEmitter
.\n\n\n
Emitted when the process is about to exit. This is a good hook to perform\nconstant time checks of the module's state (like for unit tests). The main\nevent loop will no longer be run after the 'exit' callback finishes, so\ntimers may not be scheduled.\n\n
\nExample of listening for exit
:\n\n
process.on('exit', function () {\n process.nextTick(function () {\n console.log('This will not run');\n });\n console.log('About to exit.');\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
\nExample of listening for uncaughtException
:\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.');
\nNote that uncaughtException
is a very crude mechanism for exception\nhandling. Using try / catch in your program will give you more control over\nyour program's flow. Especially for server programs that are designed to\nstay running forever, uncaughtException
can be a useful safety mechanism.\n\n\n
Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGUSR1, etc.\n\n
\nExample of listening for SIGINT
:\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});
\nAn easy way to send the SIGINT
signal is with Control-C
in most terminal\nprograms.\n\n\n
A Writable Stream
to stdout
.\n\n
Example: the definition of console.log
\n\n
console.log = function (d) {\n process.stdout.write(d + '\\n');\n};
\nprocess.stderr
and process.stdout
are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n
A writable stream to stderr.\n\n
\nprocess.stderr
and process.stdout
are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n
A Readable Stream
for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume()
to read from it.\n\n
Example of opening standard input and listening for both events:\n\n
\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function (chunk) {\n process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function () {\n process.stdout.write('end');\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});
\nThis 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
\nExample:\n\n
\n/usr/local/bin/node
\n"
},
{
"textRaw": "process.env",
"name": "env",
"desc": "An object containing the user environment. See environ(7).\n\n\n
\n" }, { "textRaw": "process.version", "name": "version", "desc": "A compiled-in property that exposes NODE_VERSION
.\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
\nconsole.log(process.versions);
\nWill output:\n\n
\n{ node: '0.4.12',\n v8: '3.1.8.26',\n ares: '1.7.4',\n ev: '4.4',\n openssl: '1.0.0e-fips' }
\n"
},
{
"textRaw": "process.installPrefix",
"name": "installPrefix",
"desc": "A compiled-in property that exposes NODE_PREFIX
.\n\n
console.log('Prefix: ' + process.installPrefix);
\n"
},
{
"textRaw": "process.pid",
"name": "pid",
"desc": "The PID of the process.\n\n
\nconsole.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
\n" }, { "textRaw": "process.arch", "name": "arch", "desc": "What processor architecture you're running on: 'arm'
, 'ia32'
, or 'x64'
.\n\n
console.log('This processor architecture is ' + process.arch);
\n"
},
{
"textRaw": "process.platform",
"name": "platform",
"desc": "What platform you're running on. 'linux2'
, 'darwin'
, etc.\n\n
console.log('This platform is ' + process.platform);
\n"
}
],
"methods": [
{
"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
\nconsole.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
\nconsole.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
To exit with a 'failure' code:\n\n
\nprocess.exit(1);
\nThe 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": "Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n
\nconsole.log('Current gid: ' + process.getgid());
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "process.setgid(id)",
"type": "method",
"name": "setgid",
"desc": "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
\nconsole.log('Current gid: ' + process.getgid());\ntry {\n process.setgid(501);\n console.log('New gid: ' + process.getgid());\n}\ncatch (err) {\n console.log('Failed to set gid: ' + err);\n}
\n",
"signatures": [
{
"params": [
{
"name": "id"
}
]
}
]
},
{
"textRaw": "process.getuid()",
"type": "method",
"name": "getuid",
"desc": "Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n
\nconsole.log('Current uid: ' + process.getuid());
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "process.setuid(id)",
"type": "method",
"name": "setuid",
"desc": "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
\nconsole.log('Current uid: ' + process.getuid());\ntry {\n process.setuid(501);\n console.log('New uid: ' + process.getuid());\n}\ncatch (err) {\n console.log('Failed to set uid: ' + err);\n}
\n",
"signatures": [
{
"params": [
{
"name": "id"
}
]
}
]
},
{
"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 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'.\nSee kill(2) for more information.\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
Example of sending a signal to yourself:\n\n
\nprocess.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",
"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
\nvar util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
\nThis will generate:\n\n
\n{ rss: 4935680,\n heapTotal: 1826816,\n heapUsed: 650472 }
\nheapTotal
and heapUsed
refer to V8's memory usage.\n\n\n
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.\n\n
process.nextTick(function () {\n console.log('nextTick callback');\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
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", "signatures": [ { "params": [] } ] } ] } ], "vars": [ { "textRaw": "require()", "type": "var", "name": "require", "desc": "To require modules. See the Modules section.\nrequire
isn't actually a global but rather local to each module.\n\n\n
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
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
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
\nExample: running node example.js
from /Users/mjr
\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
The name of the directory that the currently executing script resides in.\n\n
\nExample: running node example.js
from /Users/mjr
\n\n
console.log(__dirname);\n// /Users/mjr
\n__dirname
isn't actually a global but rather local to each module.\n\n\n
A reference to the current module. In particular\nmodule.exports
is the same as the exports
object. See src/node.js
\nfor more information.\nmodule
isn't actually a global but rather local to each module.\n\n\n
An object which is shared between all instances of the current module and\nmade accessible through require()
.\nexports
is the same as the module.exports
object. See src/node.js
\nfor more information.\nexports
isn't actually a global but rather local to each module.\n\n
See the module system documentation for more\ninformation.\n\n
\nSee the module section for more information.\n\n
\n" } ], "methods": [ { "textRaw": "setInterval(cb, ms)", "type": "method", "name": "setInterval", "desc": "The timer functions are global variables. See the timers section.\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
% 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>
\nNode'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
For example, suppose myscript.js
looked like this:\n\n
// myscript.js\nx = 5;\nsetTimeout(function () {\n debugger;\n console.log("world");\n}, 1000);\nconsole.log("hello");
\nThen 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%
\nThe 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
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
\nTo start watching an expression, type watch("my_expression")
. watchers
\nprints the active watchers. To remove a watcher, type\nunwatch("my_expression")
.\n\n
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
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
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 stdio section.\n\n
\n" }, { "textRaw": "Buffer", "name": "Buffer", "type": "global", "desc": "Used to handle binary data. See the buffer section.\n\n
\n" }, { "textRaw": "clearInterval(t)", "type": "global", "name": "clearInterval", "desc": "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
\n", "methods": [ { "textRaw": "console.log()", "type": "method", "name": "log", "desc": "Prints to stdout with newline. This function can take multiple arguments in a\nprintf()
-like way. Example:\n\n
console.log('count: %d', count);
\nIf formatting elements are not found in the first string then util.inspect
\nis used on each argument.\nSee util.format() for more information.\n\n
Same as console.log
.\n\n
Same as console.log
but prints to stderr.\n\n
Same as console.log
but prints to stderr.\n\n
Uses util.inspect
on obj
and prints resulting string to stderr.\n\n
Mark a time.\n\n\n
\n", "signatures": [ { "params": [ { "name": "label" } ] } ] }, { "textRaw": "console.timeEnd(label)", "type": "method", "name": "timeEnd", "desc": "Finish timer, record output. Example\n\n
\nconsole.time('100-elements');\nfor (var i = 0; i < 100; i++) {\n ;\n}\nconsole.timeEnd('100-elements');
\n",
"signatures": [
{
"params": [
{
"name": "label"
}
]
}
]
},
{
"textRaw": "console.trace()",
"type": "method",
"name": "trace",
"desc": "Print a stack trace to stderr of the current position.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "console.assert()", "type": "method", "name": "assert", "desc": "Same as assert.ok()
.\n\n\n
The process
object is a global object and can be accessed from anywhere.\nIt is an instance of EventEmitter
.\n\n\n
Emitted when the process is about to exit. This is a good hook to perform\nconstant time checks of the module's state (like for unit tests). The main\nevent loop will no longer be run after the 'exit' callback finishes, so\ntimers may not be scheduled.\n\n
\nExample of listening for exit
:\n\n
process.on('exit', function () {\n process.nextTick(function () {\n console.log('This will not run');\n });\n console.log('About to exit.');\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
\nExample of listening for uncaughtException
:\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.');
\nNote that uncaughtException
is a very crude mechanism for exception\nhandling. Using try / catch in your program will give you more control over\nyour program's flow. Especially for server programs that are designed to\nstay running forever, uncaughtException
can be a useful safety mechanism.\n\n\n
Emitted when the processes receives a signal. See sigaction(2) for a list of\nstandard POSIX signal names such as SIGINT, SIGUSR1, etc.\n\n
\nExample of listening for SIGINT
:\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});
\nAn easy way to send the SIGINT
signal is with Control-C
in most terminal\nprograms.\n\n\n
A Writable Stream
to stdout
.\n\n
Example: the definition of console.log
\n\n
console.log = function (d) {\n process.stdout.write(d + '\\n');\n};
\nprocess.stderr
and process.stdout
are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n
A writable stream to stderr.\n\n
\nprocess.stderr
and process.stdout
are unlike other streams in Node in\nthat writes to them are usually blocking. They are blocking in the case\nthat they refer to regular files or TTY file descriptors. In the case they\nrefer to pipes, they are non-blocking like other streams.\n\n\n
A Readable Stream
for stdin. The stdin stream is paused by default, so one\nmust call process.stdin.resume()
to read from it.\n\n
Example of opening standard input and listening for both events:\n\n
\nprocess.stdin.resume();\nprocess.stdin.setEncoding('utf8');\n\nprocess.stdin.on('data', function (chunk) {\n process.stdout.write('data: ' + chunk);\n});\n\nprocess.stdin.on('end', function () {\n process.stdout.write('end');\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});
\nThis 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
\nExample:\n\n
\n/usr/local/bin/node
\n"
},
{
"textRaw": "process.env",
"name": "env",
"desc": "An object containing the user environment. See environ(7).\n\n\n
\n" }, { "textRaw": "process.version", "name": "version", "desc": "A compiled-in property that exposes NODE_VERSION
.\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
\nconsole.log(process.versions);
\nWill output:\n\n
\n{ node: '0.4.12',\n v8: '3.1.8.26',\n ares: '1.7.4',\n ev: '4.4',\n openssl: '1.0.0e-fips' }
\n"
},
{
"textRaw": "process.installPrefix",
"name": "installPrefix",
"desc": "A compiled-in property that exposes NODE_PREFIX
.\n\n
console.log('Prefix: ' + process.installPrefix);
\n"
},
{
"textRaw": "process.pid",
"name": "pid",
"desc": "The PID of the process.\n\n
\nconsole.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
\n" }, { "textRaw": "process.arch", "name": "arch", "desc": "What processor architecture you're running on: 'arm'
, 'ia32'
, or 'x64'
.\n\n
console.log('This processor architecture is ' + process.arch);
\n"
},
{
"textRaw": "process.platform",
"name": "platform",
"desc": "What platform you're running on. 'linux2'
, 'darwin'
, etc.\n\n
console.log('This platform is ' + process.platform);
\n"
}
],
"methods": [
{
"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
\nconsole.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
\nconsole.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
To exit with a 'failure' code:\n\n
\nprocess.exit(1);
\nThe 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": "Gets the group identity of the process. (See getgid(2).)\nThis is the numerical group id, not the group name.\n\n
\nconsole.log('Current gid: ' + process.getgid());
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "process.setgid(id)",
"type": "method",
"name": "setgid",
"desc": "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
\nconsole.log('Current gid: ' + process.getgid());\ntry {\n process.setgid(501);\n console.log('New gid: ' + process.getgid());\n}\ncatch (err) {\n console.log('Failed to set gid: ' + err);\n}
\n",
"signatures": [
{
"params": [
{
"name": "id"
}
]
}
]
},
{
"textRaw": "process.getuid()",
"type": "method",
"name": "getuid",
"desc": "Gets the user identity of the process. (See getuid(2).)\nThis is the numerical userid, not the username.\n\n
\nconsole.log('Current uid: ' + process.getuid());
\n",
"signatures": [
{
"params": []
}
]
},
{
"textRaw": "process.setuid(id)",
"type": "method",
"name": "setuid",
"desc": "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
\nconsole.log('Current uid: ' + process.getuid());\ntry {\n process.setuid(501);\n console.log('New uid: ' + process.getuid());\n}\ncatch (err) {\n console.log('Failed to set uid: ' + err);\n}
\n",
"signatures": [
{
"params": [
{
"name": "id"
}
]
}
]
},
{
"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 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'.\nSee kill(2) for more information.\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
Example of sending a signal to yourself:\n\n
\nprocess.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",
"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
\nvar util = require('util');\n\nconsole.log(util.inspect(process.memoryUsage()));
\nThis will generate:\n\n
\n{ rss: 4935680,\n heapTotal: 1826816,\n heapUsed: 650472 }
\nheapTotal
and heapUsed
refer to V8's memory usage.\n\n\n
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.\n\n
process.nextTick(function () {\n console.log('nextTick callback');\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
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", "signatures": [ { "params": [] } ] } ] } ], "vars": [ { "textRaw": "require()", "type": "var", "name": "require", "desc": "To require modules. See the Modules section.\nrequire
isn't actually a global but rather local to each module.\n\n\n
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
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
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
\nExample: running node example.js
from /Users/mjr
\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
The name of the directory that the currently executing script resides in.\n\n
\nExample: running node example.js
from /Users/mjr
\n\n
console.log(__dirname);\n// /Users/mjr
\n__dirname
isn't actually a global but rather local to each module.\n\n\n
A reference to the current module. In particular\nmodule.exports
is the same as the exports
object. See src/node.js
\nfor more information.\nmodule
isn't actually a global but rather local to each module.\n\n\n
An object which is shared between all instances of the current module and\nmade accessible through require()
.\nexports
is the same as the module.exports
object. See src/node.js
\nfor more information.\nexports
isn't actually a global but rather local to each module.\n\n
See the module system documentation for more\ninformation.\n\n
\nSee the module section for more information.\n\n
\n" } ], "methods": [ { "textRaw": "setInterval(cb, ms)", "type": "method", "name": "setInterval", "desc": "The timer functions are global variables. See the timers section.\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
To schedule execution of a one-time callback
after delay
milliseconds. Returns a\ntimeoutId
for possible use with clearTimeout()
. Optionally you can\nalso pass arguments to the callback.\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
Prevents a timeout from triggering.\n\n
\n", "signatures": [ { "params": [ { "name": "timeoutId" } ] } ] }, { "textRaw": "setInterval(callback, delay, [arg], [...])", "type": "method", "name": "setInterval", "desc": "To schedule the repeated execution of callback
every delay
milliseconds.\nReturns a intervalId
for possible use with clearInterval()
. Optionally\nyou can also pass arguments to the callback.\n\n
Stops a interval from triggering.\n\n
\n", "signatures": [ { "params": [ { "name": "intervalId" } ] } ] } ], "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
The contents of foo.js
:\n\n
var circle = require('./circle.js');\nconsole.log( 'The area of a circle of radius 4 is '\n + circle.area(4));
\nThe contents of circle.js
:\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};
\nThe module circle.js
has exported the functions area()
and\ncircumference()
. To export an object, add to the special exports
\nobject.\n\n
Variables\nlocal to the module will be private. In this example the variable PI
is\nprivate to circle.js
.\n\n
The module system is implemented in the require("module")
module.\n\n
When there are circular require()
calls, a module might not be\ndone being executed when it is returned.\n\n
Consider this situation:\n\n
\na.js
:\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');
\nb.js
:\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');
\nmain.js
:\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);
\nWhen main.js
loads a.js
, then a.js
in turn loads b.js
. At that\npoint, b.js
tries to load a.js
. In order to prevent an infinite\nloop an unfinished copy of the a.js
exports object is returned to the\nb.js
module. b.js
then finishes loading, and its exports object is\nprovided to the a.js
module.\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
$ 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
\nIf 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
\nThe core modules are defined in node's source in the lib/
folder.\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
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
.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
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
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
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
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
If it is not found there, then it moves to the parent directory, and so\non, until the root of the tree is reached.\n\n
\nFor 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
/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js
This allows programs to localize their dependencies, so that they do not\nclash.\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
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
{ "name" : "some-library",\n "main" : "./lib/some-library.js" }
\nIf 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
This is the extent of Node's awareness of package.json files.\n\n
\nIf 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
./some-library/index.js
./some-library/index.node
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
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
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
To get the exact filename that will be loaded when require()
is called, use\nthe require.resolve()
function.\n\n
Putting together all of the above, here is the high-level algorithm\nin pseudocode of what require.resolve does:\n\n
\nrequire(X) from module at path Y\n1. If X is a core module,\n a. return the core module\n b. STOP\n2. If X begins with './' 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.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.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 ROOT = index of first instance of "node_modules" in PARTS, or 0\n3. let I = count of PARTS - 1\n4. let DIRS = []\n5. while I > ROOT,\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\n6. 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
Additionally, node will search in the following locations:\n\n
\n$HOME/.node_modules
$HOME/.node_libraries
$PREFIX/lib/node
Where $HOME
is the user's home directory, and $PREFIX
is node's\nconfigured installPrefix
.\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
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
require.main === module
\nFor a file foo.js
, this will be true
if run via node foo.js
, but\nfalse
if run by require('./foo')
.\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
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
Below we give a suggested directory structure that could work:\n\n
\nLet's say that we wanted to have the folder at\n/usr/lib/node/<some-package>/<some-version>
hold the contents of a\nspecific version of a package.\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
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
/usr/lib/node/foo/1.2.3/
- Contents of the foo
package, version 1.2.3./usr/lib/node/bar/4.3.2/
- Contents of the bar
package that foo
\ndepends on./usr/lib/node/foo/1.2.3/node_modules/bar
- Symbolic link to\n/usr/lib/node/bar/4.3.2/
./usr/lib/node/bar/4.3.2/node_modules/*
- Symbolic links to the packages\nthat bar
depends on.Thus, even if a cycle is encountered, or if there are dependency\nconflicts, every module will be able to get a version of its dependency\nthat it can use.\n\n
\nWhen the code in the foo
package does require('bar')
, it will get the\nversion that is symlinked into /usr/lib/node/foo/1.2.3/node_modules/bar
.\nThen, when the code in the bar
package calls require('quux')
, it'll get\nthe version that is symlinked into\n/usr/lib/node/bar/4.3.2/node_modules/quux
.\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
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
In each module, the module
free variable is a reference to the object\nrepresenting the current module. In particular\nmodule.exports
is the same as the exports
object.\nmodule
isn't actually a global but rather local to each module.\n\n
The 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
. For example suppose we\nwere making a module called a.js
\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);
\nThen in another file we could do\n\n
\nvar a = require('./a');\na.on('ready', function() {\n console.log('module a is ready');\n});
\nNote that assignment to module.exports
must be done immediately. It cannot be\ndone in any callbacks. This does not work:\n\n
x.js:\n\n
\nsetTimeout(function() {\n module.exports = { a: "hello" };\n}, 0);
\ny.js:\n\n
\nvar x = require('./x');\nconsole.log(x.a);
\n"
},
{
"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} `exports` from the resolved module ", "name": "return", "type": "Object", "desc": "`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
Note that in order to do this, you must get a reference to the module
\nobject. Since require()
returns the 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
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
\nV8 JavaScript, a C++ library. Used for interfacing with JavaScript:\ncreating objects, calling functions, etc. Documented mostly in the\nv8.h
header file (deps/v8/include/v8.h
in the Node source tree),\nwhich is also available online.
libuv, C event loop library. Anytime one\nneeds to wait for a file descriptor to become readable, wait for a timer, or\nwait for a signal to received one will need to interface with libuv. That is,\nif you perform any I/O, libuv will need to be used.
\nInternal Node libraries. Most importantly is the node::ObjectWrap
\nclass which you will likely want to derive from.
Others. Look in deps/
for what else is available.
Node statically compiles all its dependencies into the executable. When\ncompiling your module, you don't need to worry about linking to any of these\nlibraries.\n\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
\nexports.hello = function() { return 'world'; };
\nFirst we create a file hello.cc
:\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> target) {\n target->Set(String::NewSymbol("hello"),\n FunctionTemplate::New(Method)->GetFunction());\n}\nNODE_MODULE(hello, init)
\nNote that all Node addons must export an initialization function:\n\n
\nvoid Initialize (Handle<Object> target);\nNODE_MODULE(module_name, Initialize)
\nThere is no semi-colon after NODE_MODULE
as it's not a function (see node.h
).\n\n
The module_name
needs to match the filename of the final binary (minus the\n.node suffix).\n\n
The source code needs to be built into hello.node
, the binary Addon. To\ndo this we create a file called wscript
which is python code and looks\nlike this:\n\n
srcdir = '.'\nblddir = 'build'\nVERSION = '0.0.1'\n\ndef set_options(opt):\n opt.tool_options('compiler_cxx')\n\ndef configure(conf):\n conf.check_tool('compiler_cxx')\n conf.check_tool('node_addon')\n\ndef build(bld):\n obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')\n obj.target = 'hello'\n obj.source = 'hello.cc'
\nRunning node-waf configure build
will create a file\nbuild/default/hello.node
which is our Addon.\n\n
node-waf
is just WAF, the python-based build system. node-waf
is\nprovided for the ease of users.\n\n
You can now use the binary addon in a Node project hello.js
by pointing require
to\nthe recently built module:\n\n
var addon = require('./build/Release/hello');\n\nconsole.log(addon.hello()); // 'world'
\nPlease see patterns below for further information or\n
\nhttps://github.com/pietern/hiredis-node 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
\nTo compile these examples, create the wscript
file below and run\nnode-waf configure build
:\n\n
srcdir = '.'\nblddir = 'build'\nVERSION = '0.0.1'\n\ndef set_options(opt):\n opt.tool_options('compiler_cxx')\n\ndef configure(conf):\n conf.check_tool('compiler_cxx')\n conf.check_tool('node_addon')\n\ndef build(bld):\n obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')\n obj.target = 'addon'\n obj.source = ['addon.cc']
\nIn cases where there is more than one .cc
file, simply add the file name to the\nobj.source
array, e.g.:\n\n
obj.source = ['addon.cc', 'myexample.cc']
\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
#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> target) {\n target->Set(String::NewSymbol("add"),\n FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\nYou can test it with the following JavaScript snippet:\n\n
\nvar 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
#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> target) {\n target->Set(String::NewSymbol("runCallback"),\n FunctionTemplate::New(RunCallback)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\nTo test it run the following JavaScript snippet:\n\n
\nvar addon = require('./build/Release/addon');\n\naddon.runCallback(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
#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> target) {\n target->Set(String::NewSymbol("createObject"),\n FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\nTo test it in JavaScript:\n\n
\nvar addon = require('./build/Release/addon');\n\nvar obj1 = addon.createObject('hello');\nvar obj2 = addon.createObject('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> target) {\n target->Set(String::NewSymbol("createFunction"),\n FunctionTemplate::New(CreateFunction)->GetFunction());\n}\n\nNODE_MODULE(addon, Init)
\nTo test:\n\n
\nvar addon = require('./build/Release/addon');\n\nvar fn = addon.createFunction();\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
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nvoid InitAll(Handle<Object> target) {\n MyObject::Init(target);\n}\n\nNODE_MODULE(addon, InitAll)
\nThen in myobject.h
make your wrapper inherit from node::ObjectWrap
:\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> target);\n\n private:\n MyObject();\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 double counter_;\n};\n\n#endif
\nAnd 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
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nvoid MyObject::Init(Handle<Object> target) {\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\n Persistent<Function> constructor = Persistent<Function>::New(tpl->GetFunction());\n target->Set(String::NewSymbol("MyObject"), constructor);\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = new MyObject();\n obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n obj->Wrap(args.This());\n\n return args.This();\n}\n\nHandle<Value> MyObject::PlusOne(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());\n obj->counter_ += 1;\n\n return scope.Close(Number::New(obj->counter_));\n}
\nTest it with:\n\n
\nvar 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
var obj = addon.createObject();\n// instead of:\n// var obj = new addon.Object();
\nLet's register our createObject
method in addon.cc
:\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> target) {\n MyObject::Init();\n\n target->Set(String::NewSymbol("createObject"),\n FunctionTemplate::New(CreateObject)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
\nIn 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
#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 MyObject();\n ~MyObject();\n\n static v8::Persistent<v8::Function> constructor;\n static v8::Handle<v8::Value> New(const v8::Arguments& args);\n static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);\n double counter_;\n};\n\n#endif
\nThe implementation is similar to the above in myobject.cc
:\n\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nPersistent<Function> MyObject::constructor;\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\n constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = new MyObject();\n obj->counter_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n obj->Wrap(args.This());\n\n return args.This();\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->counter_ += 1;\n\n return scope.Close(Number::New(obj->counter_));\n}
\nTest it with:\n\n
\nvar addon = require('./build/Release/addon');\n\nvar obj = addon.createObject(10);\nconsole.log( obj.plusOne() ); // 11\nconsole.log( obj.plusOne() ); // 12\nconsole.log( obj.plusOne() ); // 13\n\nvar obj2 = addon.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
#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->Val() + obj2->Val();\n return scope.Close(Number::New(sum));\n}\n\nvoid InitAll(Handle<Object> target) {\n MyObject::Init();\n\n target->Set(String::NewSymbol("createObject"),\n FunctionTemplate::New(CreateObject)->GetFunction());\n\n target->Set(String::NewSymbol("add"),\n FunctionTemplate::New(Add)->GetFunction());\n}\n\nNODE_MODULE(addon, InitAll)
\nTo make things interesting we introduce a public method in myobject.h
so we\ncan probe private values after unwrapping the object:\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 Val() const { return val_; }\n\n private:\n MyObject();\n ~MyObject();\n\n static v8::Persistent<v8::Function> constructor;\n static v8::Handle<v8::Value> New(const v8::Arguments& args);\n double val_;\n};\n\n#endif
\nThe implementation of myobject.cc
is similar as before:\n\n
#define BUILDING_NODE_EXTENSION\n#include <node.h>\n#include "myobject.h"\n\nusing namespace v8;\n\nMyObject::MyObject() {};\nMyObject::~MyObject() {};\n\nPersistent<Function> MyObject::constructor;\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\n constructor = Persistent<Function>::New(tpl->GetFunction());\n}\n\nHandle<Value> MyObject::New(const Arguments& args) {\n HandleScope scope;\n\n MyObject* obj = new MyObject();\n obj->val_ = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();\n obj->Wrap(args.This());\n\n return args.This();\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}
\nTest it with:\n\n
\nvar 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": 5,
"stabilityText": "Locked",
"desc": "These functions are in the module 'util'
. Use require('util')
to access\nthem.\n\n\n
Returns a formatted string using the first argument as a printf
-like format.\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%s
- String.%d
- Number (both integer and float).%j
- JSON.%%
- single percent sign ('%'
). This does not consume an argument.If the placeholder does not have a corresponding argument, the placeholder is\nnot replaced.\n\n
\nutil.format('%s:%s', 'foo'); // 'foo:%s'
\nIf 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
util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
\nIf 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
util.format(1, 2, 3); // '1 2 3'
\n",
"signatures": [
{
"params": []
}
]
},
{
"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
require('util').debug('message on stderr');
\n",
"signatures": [
{
"params": [
{
"name": "string"
}
]
}
]
},
{
"textRaw": "util.log(string)",
"type": "method",
"name": "log",
"desc": "Output with timestamp on stdout
.\n\n
require('util').log('Timestamped message.');
\n",
"signatures": [
{
"params": [
{
"name": "string"
}
]
}
]
},
{
"textRaw": "util.inspect(object, [showHidden], [depth], [colors])",
"type": "method",
"name": "inspect",
"desc": "Return a string representation of object
, which is useful for debugging.\n\n
If showHidden
is true
, then the object's non-enumerable properties will be\nshown too. Defaults to false
.\n\n
If depth
is provided, it tells inspect
how many times to recurse while\nformatting the object. This is useful for inspecting large complicated objects.\n\n
The default is to only recurse twice. To make it recurse indefinitely, pass\nin null
for depth
.\n\n
If colors
is true
, the output will be styled with ANSI color codes.\nDefaults to false
.\n\n
Example of inspecting all properties of the util
object:\n\n
var util = require('util');\n\nconsole.log(util.inspect(util, true, null));
\n",
"signatures": [
{
"params": [
{
"name": "object"
},
{
"name": "showHidden",
"optional": true
},
{
"name": "depth",
"optional": true
},
{
"name": "colors",
"optional": true
}
]
}
]
},
{
"textRaw": "util.isArray(object)",
"type": "method",
"name": "isArray",
"desc": "Returns true
if the given "object" is an Array
. false
otherwise.\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
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
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
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",
"desc": "Experimental\n\n
\nRead 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
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
As an additional convenience, superConstructor
will be accessible\nthrough the constructor.super_
property.\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
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
\nFunctions can then be attached to objects, to be executed when an event\nis emitted. These functions are called listeners.\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
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
All EventEmitters emit the event 'newListener'
when new listeners are\nadded.\n\n
Adds a listener to the end of the listeners array for the specified event.\n\n
\nserver.on('connection', function (stream) {\n console.log('someone connected!');\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.\n\n
\nserver.on('connection', function (stream) {\n console.log('someone connected!');\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
\nserver.once('connection', function (stream) {\n console.log('Ah, we have our first user!');\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
\nvar callback = function(stream) {\n console.log('someone connected!');\n};\nserver.on('connection', callback);\n// ...\nserver.removeListener('connection', callback);
\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.\n\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. This array can be\nmanipulated, e.g. to remove listeners.\n\n
\nserver.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", "signatures": [ { "params": [ { "name": "event" }, { "name": "arg1", "optional": true }, { "name": "arg2", "optional": true }, { "name": "...", "optional": true } ] } ] } ], "events": [ { "textRaw": "Event: 'newListener'", "type": "event", "name": "newListener", "params": [], "desc": "This event is emitted any time someone adds a new listener.\n\n
\n" } ] } ] }, { "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
\nRaw 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
The Buffer
class is a global, making it very rare that one would need\nto ever require('buffer')
.\n\n
Converting between Buffers and JavaScript string objects requires an explicit\nencoding method. Here are the different string encodings.\n\n
\n'ascii'
- for 7 bit ASCII data only. This encoding method is very fast, and\nwill strip the high bit if set.\nNote that this encoding converts a null character ('\\0'
or '\\u0000'
) into\n0x20
(character code of a space). If you want to convert a null character\ninto 0x00
, you should use 'utf8'
.
'utf8'
- Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.
'ucs2'
- 2-bytes, little endian encoded Unicode characters. It can encode\nonly BMP(Basic Multilingual Plane, U+0000 - U+FFFF).
'base64'
- Base64 string encoding.
'binary'
- A way of encoding raw binary data into strings by using only\nthe first 8 bits of each character. This encoding method is deprecated and\nshould be avoided in favor of Buffer
objects where possible. This encoding\nwill be removed in future versions of Node.
'hex'
- Encode each byte as two hexidecimal characters.
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", "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
buf = new Buffer(256);\nlen = buf.write('\\u00bd + \\u00bc = \\u00be', 0);\nconsole.log(len + " bytes: " + buf.toString('utf8', 0, len));
\nThe 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
Decodes and returns a string from buffer data encoded with encoding
\n(defaults to 'utf8'
) beginning at start
(defaults to 0
) and ending at\nend
(defaults to buffer.length
).\n\n
See buffer.write()
example, above.\n\n\n
Does copy between buffers. The source and target regions can be overlapped.\ntargetStart
and sourceStart
default to 0
.\nsourceEnd
defaults to buffer.length
.\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
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"
},
{
"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.\n\n
Modifying the new buffer slice will modify memory in the original buffer!\n\n
\nExample: build a Buffer with the ASCII alphabet, take a slice, then modify one\nbyte from the original Buffer.\n\n
\nvar 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
\nSet 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
Example:\n\n
\nvar 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
\nSet 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
Example:\n\n
\nvar 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
\nSet 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
Example:\n\n
\nvar 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
\nSet 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
Example:\n\n
\nvar 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
\nSet 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
Example:\n\n
\nvar 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
\nSet 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
Works as buffer.readUInt8
, except buffer contents are treated as two's\ncomplement signed values.\n\n
Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n
\nSet 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
Works as buffer.readUInt16*
, except buffer contents are treated as two's\ncomplement signed values.\n\n
Reads a signed 16 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n
\nSet 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
Works as buffer.readUInt16*
, except buffer contents are treated as two's\ncomplement signed values.\n\n
Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n
\nSet 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
Works as buffer.readUInt32*
, except buffer contents are treated as two's\ncomplement signed values.\n\n
Reads a signed 32 bit integer from the buffer at the specified offset with\nspecified endian format.\n\n
\nSet 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
Works as buffer.readUInt32*
, except buffer contents are treated as two's\ncomplement signed values.\n\n
Reads a 32 bit float from the buffer at the specified offset with specified\nendian format.\n\n
\nSet 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
Example:\n\n
\nvar 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
\nSet 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
Example:\n\n
\nvar 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
\nSet 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
Example:\n\n
\nvar 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
\nSet 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
Example:\n\n
\nvar 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
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
Example:\n\n
\nvar 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
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
Example:\n\n
\nvar 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
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
Example:\n\n
\nvar 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
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
Example:\n\n
\nvar 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
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
Example:\n\n
\nvar 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
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
Works as buffer.writeUInt8
, except value is written out as a two's complement\nsigned integer into buffer
.\n\n
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
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
Works as buffer.writeUInt16*
, except value is written out as a two's\ncomplement signed integer into buffer
.\n\n
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
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
Works as buffer.writeUInt16*
, except value is written out as a two's\ncomplement signed integer into buffer
.\n\n
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
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
Works as buffer.writeUInt32*
, except value is written out as a two's\ncomplement signed integer into buffer
.\n\n
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
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
Works as buffer.writeUInt32*
, except value is written out as a two's\ncomplement signed integer into buffer
.\n\n
Writes value
to the buffer at the specified offset with specified endian\nformat. Note, value
must be a valid 32 bit float.\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
Example:\n\n
\nvar 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, value
must be a valid 32 bit float.\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
Example:\n\n
\nvar 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
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
Example:\n\n
\nvar 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
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
Example:\n\n
\nvar 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
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
Example: copy an ASCII string into a buffer, one byte at a time:\n\n
\nstr = "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
buf = new Buffer(1234);\n\nconsole.log(buf.length);\nbuf.write("some string", "ascii", 0);\nconsole.log(buf.length);\n\n// 1234\n// 1234
\n",
"shortDesc": "Number"
}
],
"classMethods": [
{
"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
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
Example:\n\n
\nstr = '\\u00bd + \\u00bc = \\u00be';\n\nconsole.log(str + ": " + str.length + " characters, " +\n Buffer.byteLength(str, 'utf8') + " bytes");\n\n// ½ + ¼ = ¾: 9 characters, 12 bytes
\n"
}
],
"signatures": [
{
"params": [
{
"textRaw": "`size` Number ",
"name": "size",
"desc": "Number"
}
],
"desc": "Allocates a new buffer of size
octets.\n\n
Allocates a new buffer of size
octets.\n\n
Allocates a new buffer using an array
of octets.\n\n
Allocates a new buffer using an array
of octets.\n\n
Allocates a new buffer containing the given str
.\nencoding
defaults to 'utf8'
.\n\n
Allocates a new buffer containing the given str
.\nencoding
defaults to 'utf8'
.\n\n
This class is primarily for internal use. JavaScript programs should\nuse Buffer instead of using SlowBuffer.\n\n
\nIn 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
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
A stream is an abstract interface implemented by various objects in Node.\nFor example a request to an HTTP server is a stream, as is stdout. Streams\nare readable, writable, or both. All streams are instances of EventEmitter
.\n\n
You can load up the Stream base class by doing require('stream')
.\n\n
A Readable Stream
has the following methods, members, and events.\n\n
function (data) { }
\n\n
The 'data'
event emits either a Buffer
(by default) or a string if\nsetEncoding()
was used.\n\n
Note that the data will be lost if there is no listener when a\nReadable Stream
emits a 'data'
event.\n\n
function () { }
\n\n
Emitted when the stream has received an EOF (FIN in TCP terminology).\nIndicates that no more 'data'
events will happen. If the stream is also\nwritable, it may be possible to continue writing.\n\n
function (exception) { }
\n\n
Emitted if there was an error receiving data.\n\n
\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "function () { }
\n\n
Emitted when the underlying file descriptor has been closed. Not all streams\nwill emit this. (For example, an incoming HTTP request will not emit\n'close'
.)\n\n
A boolean that is true
by default, but turns false
after an 'error'
\noccurred, the stream came to an 'end'
, or destroy()
was called.\n\n
Makes the data event emit a string instead of a Buffer
. encoding
can be\n'utf8'
, 'ascii'
, or 'base64'
.\n\n
Pauses the incoming 'data'
events.\n\n
Resumes the incoming 'data'
events after a pause()
.\n\n
Closes the underlying file descriptor. Stream will not emit any more events.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "stream.pipe(destination, [options])", "type": "method", "name": "pipe", "desc": "This is a Stream.prototype
method available on all Stream
s.\n\n
Connects this read stream to destination
WriteStream. Incoming\ndata on this stream gets written to destination
. The destination and source\nstreams are kept in sync by pausing and resuming as necessary.\n\n
This function returns the destination
stream.\n\n
Emulating the Unix cat
command:\n\n
process.stdin.resume();\nprocess.stdin.pipe(process.stdout);
\nBy default end()
is called on the destination when the source stream emits\nend
, so that destination
is no longer writable. Pass { end: false }
as\noptions
to keep the destination stream open.\n\n
This keeps process.stdout
open so that "Goodbye" can be written at the end.\n\n
process.stdin.resume();\n\nprocess.stdin.pipe(process.stdout, { end: false });\n\nprocess.stdin.on("end", function() {\n process.stdout.write("Goodbye\\n");\n});
\n",
"signatures": [
{
"params": [
{
"name": "destination"
},
{
"name": "options",
"optional": true
}
]
}
]
}
]
},
{
"textRaw": "Writable Stream",
"name": "Writable Stream",
"type": "class",
"desc": "A Writable Stream
has the following methods, members, and events.\n\n
function () { }
\n\n
After a write()
method returned false
, this event is emitted to\nindicate that it is safe to write again.\n\n
function (exception) { }
\n\n
Emitted on error with the exception exception
.\n\n
function () { }
\n\n
Emitted when the underlying file descriptor has been closed.\n\n
\n", "params": [] }, { "textRaw": "Event: 'pipe'", "type": "event", "name": "pipe", "desc": "function (src) { }
\n\n
Emitted when the stream is passed to a readable stream's pipe method.\n\n
\n", "params": [] } ], "properties": [ { "textRaw": "stream.writable", "name": "writable", "desc": "A boolean that is true
by default, but turns false
after an 'error'
\noccurred or end()
/ destroy()
was called.\n\n
Writes string
with the given encoding
to the stream. Returns true
if\nthe string has been flushed to the kernel buffer. Returns false
to\nindicate that the kernel buffer is full, and the data will be sent out in\nthe future. The 'drain'
event will indicate when the kernel buffer is\nempty again. The encoding
defaults to 'utf8'
.\n\n
If the optional fd
parameter is specified, it is interpreted as an integral\nfile descriptor to be sent over the stream. This is only supported for UNIX\nstreams, and is silently ignored otherwise. When writing a file descriptor in\nthis manner, closing the descriptor before the stream drains risks sending an\ninvalid (closed) FD.\n\n
Same as the above except with a raw buffer.\n\n
\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "stream.end()", "type": "method", "name": "end", "desc": "Terminates the stream with EOF or FIN.\nThis call will allow queued write data to be sent before closing the stream.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "stream.end(string, encoding)", "type": "method", "name": "end", "desc": "Sends string
with the given encoding
and terminates the stream with EOF\nor FIN. This is useful to reduce the number of packets sent.\n\n
Same as above but with a buffer
.\n\n
Closes the underlying file descriptor. Stream will not emit any more events.\nAny queued write data will not be sent.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "stream.destroySoon()", "type": "method", "name": "destroySoon", "desc": "After the write queue is drained, close the file descriptor. destroySoon()
\ncan still destroy straight away, as long as there is no data left in the queue\nfor writes.\n\n
Use require('crypto')
to access this module.\n\n
The crypto module requires OpenSSL to be available on the underlying platform.\nIt offers a way of encapsulating secure credentials to be used as part\nof a secure HTTPS net or http connection.\n\n
\nIt also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.\n\n
\n", "methods": [ { "textRaw": "crypto.createCredentials(details)", "type": "method", "name": "createCredentials", "desc": "Creates a credentials object, with the optional details being a dictionary with keys:\n\n
\npfx
: A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificateskey
: a string holding the PEM encoded private keycert
: a string holding the PEM encoded certificatepassphrase
: A string of passphrase for the private key or pfxca
: either a string or list of strings of PEM encoded CA certificates to trust.ciphers
: a string describing the ciphers to use or exclude. Consult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details\non the format.If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in\n
\nhttp://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 algorithm\nwhich can be used to generate hash digests.\n\n
\nalgorithm
is dependent on the available algorithms supported by the version\nof OpenSSL on the platform. Examples are 'sha1'
, 'md5'
, 'sha256'
, 'sha512'
, etc.\nOn recent releases, openssl list-message-digest-algorithms
will display the available digest algorithms.\n\n
Example: this program that takes the sha1 sum of a file\n\n
\nvar 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 algorithm and key.\n\n
\nalgorithm
is dependent on the available algorithms supported by OpenSSL - see createHash above.\nkey
is the hmac key to be used.\n\n
Creates and returns a cipher object, with the given algorithm and password.\n\n
\nalgorithm
is dependent on OpenSSL, examples are 'aes192'
, etc.\nOn recent releases, openssl list-cipher-algorithms
will display the\navailable cipher algorithms.\npassword
is used to derive key and IV, which must be 'binary'
encoded\nstring (See the Buffer section for more information).\n\n
Creates and returns a cipher object, with the given algorithm, key and iv.\n\n
\nalgorithm
is the same as the createCipher()
. key
is a raw key used in\nalgorithm. iv
is an Initialization vector. key
and iv
must be 'binary'
\nencoded string (See the Buffer section for more information).\n\n
Creates and returns a decipher object, with the given algorithm and key.\nThis 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 and iv.\nThis 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.\nOn recent OpenSSL releases, openssl list-public-key-algorithms
will display\nthe available signing algorithms. Examples are 'RSA-SHA256'
.\n\n
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 the\ngiven bit length. The generator used is 2
.\n\n
Creates a Diffie-Hellman key exchange object using the supplied prime. The\ngenerator used is 2
. Encoding can be 'binary'
, 'hex'
, or 'base64'
.\nDefaults to 'binary'
.\n\n
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
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}
\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
\nReturned by crypto.createHash
.\n\n
Updates the hash content with the given data
, the encoding of which is given\nin input_encoding
and can be 'utf8'
, 'ascii'
or 'binary'
.\nDefaults to 'binary'
.\nThis can be called many times with new data as it is streamed.\n\n
Calculates the digest of all of the passed data to be hashed.\nThe encoding
can be 'hex'
, 'binary'
or 'base64'
.\nDefaults to 'binary'
.\n\n
Note: hash
object can not be used after digest()
method been called.\n\n\n
Class for creating cryptographic hmac content.\n\n
\nReturned by crypto.createHmac
.\n\n
Update the hmac content with the given data
.\nThis can be called many times with new data as it is streamed.\n\n
Calculates the digest of all of the passed data to the hmac.\nThe encoding
can be 'hex'
, 'binary'
or 'base64'
.\nDefaults to 'binary'
.\n\n
Note: hmac
object can not be used after digest()
method been called.\n\n\n
Class for encrypting data.\n\n
\nReturned by crypto.createCipher
and crypto.createCipheriv
.\n\n
Updates the cipher with data
, the encoding of which is given in\ninput_encoding
and can be 'utf8'
, 'ascii'
or 'binary'
.\nDefaults to 'binary'
.\n\n
The output_encoding
specifies the output format of the enciphered data,\nand can be 'binary'
, 'base64'
or 'hex'
. Defaults to 'binary'
.\n\n
Returns the enciphered contents, and can be called many times with new data 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
being one of:\n'binary'
, 'base64'
or 'hex'
. Defaults to 'binary'
.\n\n
Note: cipher
object can not be used after final()
method been called.\n\n\n
Class for decrypting data.\n\n
\nReturned by crypto.createDecipher
and crypto.createDecipheriv
.\n\n
Updates the decipher with data
, which is encoded in 'binary'
, 'base64'
\nor 'hex'
. Defaults to 'binary'
.\n\n
The output_decoding
specifies in what format to return the deciphered\nplaintext: 'binary'
, 'ascii'
or 'utf8'
. Defaults to 'binary'
.\n\n
Returns any remaining plaintext which is deciphered,\nwith output_encoding
being one of: 'binary'
, 'ascii'
or 'utf8'
.\nDefaults to 'binary'
.\n\n
Note: decipher
object can not be used after final()
method been called.\n\n\n
Class for generating signatures.\n\n
\nReturned by crypto.createSign
.\n\n
Updates the signer object with data.\nThis can be called many times with new data as it is streamed.\n\n
\n", "signatures": [ { "params": [ { "name": "data" } ] } ] }, { "textRaw": "signer.sign(private_key, [output_format])", "type": "method", "name": "sign", "desc": "Calculates the signature on all the updated data passed through the signer.\nprivate_key
is a string containing the PEM encoded private key for signing.\n\n
Returns the signature in output_format
which can be 'binary'
, 'hex'
or\n'base64'
. Defaults to 'binary'
.\n\n
Note: signer
object can not be used after sign()
method been called.\n\n
Class for verifying signatures.\n\n
\nReturned by crypto.createVerify
.\n\n
Updates the verifier object with data.\nThis can be called many times with 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
. object
is a\nstring containing a PEM encoded object, which can be one of RSA public key,\nDSA public key, or X.509 certificate. signature
is the previously calculated\nsignature for the data, in the signature_format
which can be 'binary'
,\n'hex'
or 'base64'
. Defaults to 'binary'
.\n\n
Returns true or false depending on the validity of the signature for the data and public key.\n\n
\nNote: verifier
object can not be used after verify()
method been called.\n\n
The class for creating Diffie-Hellman key exchanges.\n\n
\nReturned by crypto.createDiffieHellman
.\n\n
Generates private and public Diffie-Hellman key values, and returns the\npublic key in the specified encoding. This key should be transferred to the\nother party. Encoding can be 'binary'
, 'hex'
, or 'base64'
.\nDefaults to 'binary'
.\n\n
Computes the shared secret using other_public_key
as the other party's\npublic key and returns the computed shared secret. Supplied key is\ninterpreted using specified input_encoding
, and secret is encoded using\nspecified output_encoding
. Encodings can be 'binary'
, 'hex'
, or\n'base64'
. The input encoding defaults to 'binary'
.\nIf no output encoding is given, the input encoding is used as output encoding.\n\n
Returns the Diffie-Hellman prime in the specified encoding, which can be\n'binary'
, 'hex'
, or 'base64'
. Defaults to 'binary'
.\n\n
Returns the Diffie-Hellman prime in the specified encoding, which can be\n'binary'
, 'hex'
, or 'base64'
. Defaults to 'binary'
.\n\n
Returns the Diffie-Hellman public key in the specified encoding, which can\nbe 'binary'
, 'hex'
, or 'base64'
. Defaults to 'binary'
.\n\n
Returns the Diffie-Hellman private key in the specified encoding, which can\nbe 'binary'
, 'hex'
, or 'base64'
. Defaults to 'binary'
.\n\n
Sets the Diffie-Hellman public key. Key encoding can be 'binary'
, 'hex'
,\nor 'base64'
. Defaults to 'binary'
.\n\n
Sets the Diffie-Hellman private key. Key encoding can be 'binary'
, 'hex'
,\nor 'base64'
. Defaults to 'binary'
.\n\n
Use require('tls')
to access this module.\n\n
The tls
module uses OpenSSL to provide Transport Layer Security and/or\nSecure Socket Layer: encrypted stream communication.\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
\nopenssl genrsa -out ryans-key.pem 1024
\nAll severs 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
\nopenssl req -new -key ryans-key.pem -out ryans-csr.pem
\nTo create a self-signed certificate with the CSR, do this:\n\n
\nopenssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
\nAlternatively 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
To create .pfx or .p12, do this:\n\n
\nopenssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \\\n -certfile ca-cert.pem -out agent5.pfx
\nin
: certificateinkey
: private keycertfile
: all CA certs concatenated in one file like\ncat ca1-cert.pem ca2-cert.pem > ca-cert.pem
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
\nTo mitigate this, renegotiations are limited to three times every 10 minutes. An\nerror is emitted on the CleartextStream instance when\nthe threshold is exceeded. The limits are configurable:\n\n
\ntls.CLIENT_RENEG_LIMIT
: renegotiation limit, default is 3.
tls.CLIENT_RENEG_WINDOW
: renegotiation window in seconds, default is
10 minutes.
\nDon't change the defaults unless you know what you are doing.\n\n
\nTo 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
NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS\nhandshake extensions allowing you:\n\n
\nCreates a new tls.Server.\nThe connectionListener
argument is automatically set as a listener for the\nsecureConnection event.\nThe options
object has these possibilities:\n\n
pfx
: A string or Buffer
containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format. (Mutually exclusive with\nthe key
, cert
and ca
options.)
key
: A string or Buffer
containing the private key of the server in\nPEM format. (Required)
passphrase
: A string of passphrase for the private key or pfx.
cert
: A string or Buffer
containing the certificate key of the server in\nPEM format. (Required)
ca
: An array of strings or Buffer
s of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.
ciphers
: A string describing the ciphers to use or exclude. Consult\nhttp://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for\ndetails on the format.
requestCert
: If true
the server will request a certificate from\nclients that connect and attempt to verify that certificate. Default:\nfalse
.
rejectUnauthorized
: If true
the server will reject any connection\nwhich is not authorized with the list of supplied CAs. This option only\nhas an effect if requestCert
is true
. Default: false
.
NPNProtocols
: An array or Buffer
of possible NPN protocols. (Protocols\nshould be ordered by their priority).
SNICallback
: A function that will be called if client supports SNI TLS\nextension. Only one argument will be passed to it: servername
. And\nSNICallback
should return SecureContext instance.\n(You can use crypto.createCredentials(...).context
to get proper\nSecureContext). If SNICallback
wasn't provided - default callback with\nhigh-level API will be used (see below).
sessionIdContext
: A string containing a opaque identifier for session\nresumption. If requestCert
is true
, the default is MD5 hash value\ngenerated from command-line. Otherwise, the default is not provided.
Here is a simple example echo server:\n\n
\nvar 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});
\nOr\n\n
\nvar 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});
\nYou can test this server by connecting to it with openssl s_client
:\n\n\n
openssl s_client -connect 127.0.0.1:8000
\n",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "secureConnectionListener",
"optional": true
}
]
}
]
},
{
"textRaw": "tls.connect(port, [host], [options], [secureConnectListener])",
"type": "method",
"name": "connect",
"desc": "Creates a new client connection to the given port
and host
. (If host
\ndefaults to localhost
.) options
should be an object which specifies\n\n
pfx
: A string or Buffer
containing the private key, certificate and\nCA certs of the server in PFX or PKCS12 format.
key
: A string or Buffer
containing the private key of the client in\nPEM format.
passphrase
: A string of passphrase for the private key or pfx.
cert
: A string or Buffer
containing the certificate key of the client in\nPEM format.
ca
: An array of strings or Buffer
s of trusted certificates. If this is\nomitted several well known "root" CAs will be used, like VeriSign.\nThese are used to authorize connections.
NPNProtocols
: An array of string or Buffer
containing supported NPN\nprotocols. Buffer
should have following format: 0x05hello0x05world
,\nwhere first byte is next protocol name's length. (Passing array should\nusually be much simpler: ['hello', 'world']
.)
servername
: Servername for SNI (Server Name Indication) TLS extension.
socket
: Establish secure connection on a given socket rather than\ncreating a new socket. If this option is specified, host
and port
\nare ignored. This is intended FOR INTERNAL USE ONLY. As with all\nundocumented APIs in Node, they should not be used.
The secureConnectListener
parameter will be added as a listener for the\n'secureConnect' event.\n\n
tls.connect()
returns a CleartextStream object.\n\n
Here is an example of a client of echo server as described previously:\n\n
\nvar 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});
\nOr\n\n
\nvar 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": "secureConnectListener",
"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
\ncredentials
: A credentials object from crypto.createCredentials( ... )
isServer
: A boolean indicating whether this tls connection should be\nopened as a server or a client.
requestCert
: A boolean indicating whether a server should request a\ncertificate from a connecting client. Only applies to server connections.
rejectUnauthorized
: A boolean indicating whether a server should\nautomatically reject clients with invalid certificates. Only applies to\nservers with requestCert
enabled.
tls.createSecurePair()
returns a SecurePair object with\ncleartext and encrypted
stream properties.\n\n
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
\nSimilarly 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
function (cleartextStream) {}
\n\n
This event is emitted after a new connection has been successfully\nhandshaked. The argument is a instance of\nCleartextStream. It has all the common stream methods\nand events.\n\n
\ncleartextStream.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
function (exception) { }
\n\n
When a client connection emits an 'error' event before secure connection is\nestablished - it will be forwarded here.\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
This function is asynchronous. The last parameter callback
will be called\nwhen the server has been bound.\n\n
See net.Server
for more information.\n\n\n
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
Returns the bound address and port of the server as reported by the operating\nsystem.\nSee net.Server.address() for more 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
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: 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
\nThis instance implements a duplex Stream interfaces.\nIt has all the common stream methods and events.\n\n
\nA ClearTextStream is the clear
member of a SecurePair object.\n\n
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
A boolean that is true
if the peer certificate was signed by one of the\nspecified CAs, otherwise false
\n\n
The reason why the peer's certificate has not been verified. This property\nbecomes available only when cleartextStream.authorized === false
.\n\n
The string representation of the remote IP address. For example,\n'74.125.127.100'
or '2001:4860:a005::68'
.\n\n
The numeric representation of the remote port. For example, 443
.\n\n\n
Returns an object representing the peer's certificate. The returned object has\nsome properties corresponding to the field of the certificate.\n\n
\nExample:\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' }
\nIf the peer does not provide a certificate, it returns null
or an empty\nobject.\n\n
Returns the bound address and port of the underlying socket as reported by the\noperating system. Returns an object with two properties, e.g.\n{"address":"192.168.57.1", "port":62053}
\n\n
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
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
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
\nHere is an example of the asynchronous version:\n\n
\nvar fs = require('fs');\n\nfs.unlink('/tmp/hello', function (err) {\n if (err) throw err;\n console.log('successfully deleted /tmp/hello');\n});
\nHere is the synchronous version:\n\n
\nvar fs = require('fs');\n\nfs.unlinkSync('/tmp/hello')\nconsole.log('successfully deleted /tmp/hello');
\nWith the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:\n\n
\nfs.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});
\nIt could be that fs.stat
is executed before fs.rename
.\nThe correct way to do this is to chain the callbacks.\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});
\nIn busy processes, the programmer is strongly encouraged to use the\nasynchronous versions of these calls. The synchronous versions will block\nthe entire process until they complete--halting all connections.\n\n
\nRelative path to filename can be used, remember however that this path will be relative\nto process.cwd()
.\n\n
Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "path1" }, { "name": "path2" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "fs.renameSync(path1, path2)", "type": "method", "name": "renameSync", "desc": "Synchronous rename(2).\n\n
\n", "signatures": [ { "params": [ { "name": "path1" }, { "name": "path2" } ] } ] }, { "textRaw": "fs.truncate(fd, len, [callback])", "type": "method", "name": "truncate", "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", "optional": true } ] } ] }, { "textRaw": "fs.truncateSync(fd, len)", "type": "method", "name": "truncateSync", "desc": "Synchronous ftruncate(2).\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "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", "optional": true } ] } ] }, { "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", "optional": true } ] } ] }, { "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", "optional": true } ] } ] }, { "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", "optional": true } ] } ] }, { "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", "optional": true } ] } ] }, { "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", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback", "optional": true } ] } ] }, { "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
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
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
Synchronous stat(2). Returns an instance of fs.Stats
.\n\n
Synchronous lstat(2). Returns an instance of fs.Stats
.\n\n
Synchronous fstat(2). Returns an instance of fs.Stats
.\n\n
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", "optional": true } ] } ] }, { "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(linkdata, path, [type], [callback])", "type": "method", "name": "symlink", "desc": "Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback.\ntype
argument can be either 'dir'
or 'file'
(default is 'file'
). It is only \nused on Windows (ignored on other platforms).\n\n
Synchronous symlink(2).\n\n
\n", "signatures": [ { "params": [ { "name": "linkdata" }, { "name": "path" }, { "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
Synchronous readlink(2). Returns the symbolic link's string value.\n\n
\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.realpath(path, [callback])", "type": "method", "name": "realpath", "desc": "Asynchronous realpath(2). The callback gets two arguments (err,\nresolvedPath)
. May use process.cwd
to resolve relative paths.\n\n
Synchronous realpath(2). Returns the resolved path.\n\n
\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "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", "optional": true } ] } ] }, { "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", "optional": true } ] } ] }, { "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
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
Synchronous readdir(3). Returns an array of filenames excluding '.'
and\n'..'
.\n\n
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", "optional": true } ] } ] }, { "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
'r'
- Open file for reading.\nAn exception occurs if the file does not exist.
'r+'
- Open file for reading and writing.\nAn exception occurs if the file does not exist.
'w'
- Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'w+'
- Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'a'
- Open file for appending.\nThe file is created if it does not exist.
'a+'
- Open file for reading and appending.\nThe file is created if it does not exist.
mode
defaults to 0666
. The callback gets two arguments (err, fd)
.\n\n
Synchronous open(2).\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", "optional": true } ] } ] }, { "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", "optional": true } ] } ] }, { "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", "optional": true } ] } ] }, { "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
offset
and length
determine the part of the buffer to be written.\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
The callback will be given three arguments (err, written, buffer)
where written
\nspecifies how many bytes were written from buffer
.\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
Synchronous version of buffer-based fs.write()
. Returns the number of bytes\nwritten.\n\n
Synchronous version of string-based fs.write()
. encoding
defaults to\n'utf8'
. Returns the number of bytes written.\n\n
Read data from the file specified by fd
.\n\n
buffer
is the buffer that the data will be written to.\n\n
offset
is offset within the buffer where writing will start.\n\n
length
is an integer specifying the number of bytes to read.\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
The callback is given the three arguments, (err, bytesRead, buffer)
.\n\n
Synchronous version of buffer-based fs.read
. Returns the number of\nbytesRead
.\n\n
Synchronous version of string-based fs.read
. Returns the number of\nbytesRead
.\n\n
Asynchronously reads the entire contents of a file. Example:\n\n
\nfs.readFile('/etc/passwd', function (err, data) {\n if (err) throw err;\n console.log(data);\n});
\nThe callback is passed two arguments (err, data)
, where data
is the\ncontents of the file.\n\n
If no encoding is specified, then the raw buffer is returned.\n\n\n
\n", "signatures": [ { "params": [ { "name": "filename" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "fs.readFileSync(filename, [encoding])", "type": "method", "name": "readFileSync", "desc": "Synchronous version of fs.readFile
. Returns the contents of the filename
.\n\n
If encoding
is specified then this function returns a string. Otherwise it\nreturns a buffer.\n\n\n
Asynchronously writes data to a file, replacing the file if it already exists.\ndata
can be a string or a buffer. The encoding
argument is ignored if\ndata
is a buffer. It defaults to 'utf8'
.\n\n
Example:\n\n
\nfs.writeFile('message.txt', 'Hello Node', function (err) {\n if (err) throw err;\n console.log('It\\'s saved!');\n});
\n",
"signatures": [
{
"params": [
{
"name": "filename"
},
{
"name": "data"
},
{
"name": "encoding",
"optional": true
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "fs.writeFileSync(filename, data, [encoding])",
"type": "method",
"name": "writeFileSync",
"desc": "The synchronous version of fs.writeFile
.\n\n
Watch for changes on filename
. The callback listener
will be called each\ntime the file is accessed.\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. (On Linux systems with inotify, interval
is ignored.) The\ndefault is { persistent: true, interval: 0 }
.\n\n
The listener
gets two arguments the current stat object and the previous\nstat object:\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});
\nThese stat objects are instances of fs.Stat
.\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
Stop watching for changes on filename
.\n\n
Watch for changes on filename
, where filename
is either a file or a\ndirectory. The returned object is a fs.FSWatcher.\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
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
The fs.watch
API is not 100% consistent across platforms, and is\nunavailable in some situations.\n\n
This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.\n\n
\ninotify
.kqueue
.event ports
.ReadDirectoryChangesW
.If the underlying functionality is not available for some reason, then\nfs.watch
will not be able to function. You can still use\nfs.watchFile
, which uses stat polling, but it is slower and less\nreliable.\n\n
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
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"
}
]
}
]
},
{
"textRaw": "fs.createReadStream(path, [options])",
"type": "method",
"name": "createReadStream",
"desc": "Returns a new ReadStream object (See Readable Stream
).\n\n
options
is an object with the following defaults:\n\n
{ flags: 'r',\n encoding: null,\n fd: null,\n mode: 0666,\n bufferSize: 64 * 1024\n}
\noptions
can include start
and end
values to read a range of bytes from\nthe file instead of the entire file. Both start
and end
are inclusive and\nstart at 0.\n\n
An example to read the last 10 bytes of a file which is 100 bytes long:\n\n
\nfs.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
options
is an object with the following defaults:\n\n
{ flags: 'w',\n encoding: null,\n mode: 0666 }
\noptions
may also include a start
option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags
mode of r+
rather than the\ndefault mode w
.\n\n
Objects returned from fs.stat()
, fs.lstat()
and fs.fstat()
and their\nsynchronous counterparts are of this type.\n\n
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(only valid with fs.lstat()
)stats.isFIFO()
stats.isSocket()
For a regular file util.inspect(stats)
would return a string very\nsimilar to this:\n\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 }
\nPlease 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
ReadStream
is a Readable Stream.\n\n
Emitted when the ReadStream's file is opened.\n\n\n
\n" } ] }, { "textRaw": "Class: fs.FSWatcher", "type": "class", "name": "fs.FSWatcher", "desc": "Objects returned from fs.watch()
are of this type.\n\n
Stop watching for changes on the given fs.FSWatcher
.\n\n
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" } ] } ], "properties": [ { "textRaw": "fs.WriteStream", "name": "WriteStream", "desc": "WriteStream
is a Writable Stream.\n\n
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" } ] } ], "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
\npath.exists
and path.existsSync
are the exceptions, and should\nlogically be found in the fs module as they do access the file system.\n\n
Use require('path')
to use this module. The following methods are provided:\n\n
Normalize a string path, taking care of '..'
and '.'
parts.\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
\nExample:\n\n
\npath.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.\nNon-string arguments are ignored.\n\n
\nExample:\n\n
\npath.join('/foo', 'bar', 'baz/asdf', 'quux', '..')\n// returns\n'/foo/bar/baz/asdf'\n\npath.join('foo', {}, 'bar')\n// returns\n'foo/bar'
\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
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 arguments are ignored.\n\n
Another way to think of it is as a sequence of cd
commands in a shell.\n\n
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
\nIs similar to:\n\n
\ncd foo/bar\ncd /tmp/file/\ncd ..\ncd a/../subfile\npwd
\nThe difference is that the different paths don't need to exist and may also be\nfiles.\n\n
\nExamples:\n\n
\npath.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
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
path.resolve(from, path.relative(from, to)) == path.resolve(to)
\nExamples:\n\n
\npath.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
Example:\n\n
\npath.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
Example:\n\n
\npath.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
\npath.extname('index.html')\n// returns\n'.html'\n\npath.extname('index.')\n// returns\n'.'\n\npath.extname('index')\n// returns\n''
\n",
"signatures": [
{
"params": [
{
"name": "p"
}
]
}
]
},
{
"textRaw": "path.exists(p, [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
path.exists('/etc/passwd', function (exists) {\n util.debug(exists ? "it's there" : "no passwd!");\n});
\n",
"signatures": [
{
"params": [
{
"name": "p"
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "path.existsSync(p)",
"type": "method",
"name": "existsSync",
"desc": "Synchronous version of path.exists
.\n\n
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
Creates a new TCP server. The connectionListener
argument is\nautomatically set as a listener for the 'connection'\nevent.\n\n
options
is an object with the following defaults:\n\n
{ allowHalfOpen: false\n}
\nIf allowHalfOpen
is true
, then the socket won't automatically send 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
Here is an example of a echo server which listens for connections\non port 8124:\n\n
\nvar net = require('net');\nvar server = net.createServer(function(c) { //'connection' listener\n console.log('server connected');\n c.on('end', function() {\n console.log('server 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});
\nTest this by using telnet
:\n\n
telnet localhost 8124
\nTo listen on the socket /tmp/echo.sock
the third line from the last would\njust be changed to\n\n
server.listen('/tmp/echo.sock', function() { //'listening' listener
\nUse nc
to connect to a UNIX domain socket server:\n\n
nc -U /tmp/echo.sock
\n",
"signatures": [
{
"params": [
{
"name": "options",
"optional": true
},
{
"name": "connectionListener",
"optional": true
}
]
}
]
},
{
"textRaw": "net.connect(arguments...)",
"type": "method",
"name": "connect",
"desc": "Construct a new socket object and opens a socket to the given location. When\nthe socket is established the 'connect' event will be\nemitted.\n\n
\nThe arguments for these methods change the type of connection:\n\n
\nnet.connect(port, [host], [connectListener])
net.createConnection(port, [host], [connectListener])
Creates a TCP connection to port
on host
. If host
is omitted,\n'localhost'
will be assumed.
net.connect(path, [connectListener])
net.createConnection(path, [connectListener])
Creates unix socket connection to path
.
The connectListener
parameter will be added as an listener for the\n'connect' event.\n\n
Here is an example of a client of echo server as described previously:\n\n
\nvar net = require('net');\nvar client = net.connect(8124, function() { //'connect' listener\n console.log('client connected');\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('client disconnected');\n});
\nTo connect on the socket /tmp/echo.sock
the second line would just be\nchanged to\n\n
var client = net.connect('/tmp/echo.sock', function() { //'connect' listener
\n",
"signatures": [
{
"params": [
{
"name": "arguments..."
}
]
},
{
"params": [
{
"name": "arguments..."
}
]
}
]
},
{
"textRaw": "net.createConnection(arguments...)",
"type": "method",
"name": "createConnection",
"desc": "Construct a new socket object and opens a socket to the given location. When\nthe socket is established the 'connect' event will be\nemitted.\n\n
\nThe arguments for these methods change the type of connection:\n\n
\nnet.connect(port, [host], [connectListener])
net.createConnection(port, [host], [connectListener])
Creates a TCP connection to port
on host
. If host
is omitted,\n'localhost'
will be assumed.
net.connect(path, [connectListener])
net.createConnection(path, [connectListener])
Creates unix socket connection to path
.
The connectListener
parameter will be added as an listener for the\n'connect' event.\n\n
Here is an example of a client of echo server as described previously:\n\n
\nvar net = require('net');\nvar client = net.connect(8124, function() { //'connect' listener\n console.log('client connected');\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('client disconnected');\n});
\nTo connect on the socket /tmp/echo.sock
the second line would just be\nchanged to\n\n
var client = net.connect('/tmp/echo.sock', function() { //'connect' listener
\n",
"signatures": [
{
"params": [
{
"name": "arguments..."
}
]
}
]
},
{
"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
\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.\nA server is a net.Socket
that can listen for new incoming connections.\n\n
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
This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nthe last parameter listeningListener
will be added as an listener for the\n'listening' event.\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
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
Start a UNIX socket server listening for connections on the given path
.\n\n
This function is asynchronous. When the server has been bound,\n'listening' event will be emitted.\nthe last parameter listeningListener
will be added as an listener for the\n'listening' event.\n\n
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
Returns the bound address and port of the server as reported by the operating system.\nUseful to find which port was assigned when giving getting an OS-assigned address.\nReturns an object with two properties, e.g. {"address":"127.0.0.1", "port":2121}
\n\n
Example:\n\n
\nvar 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});
\nDon't call server.address()
until the 'listening'
event has been emitted.\n\n
Set this property to reject connections when the server's connection count gets\nhigh.\n\n
\n" }, { "textRaw": "server.connections", "name": "connections", "desc": "The number of concurrent connections on the server.\n\n\n
\nnet.Server
is an EventEmitter
with the following events:\n\n
Emitted when the server has been bound after calling server.listen
.\n\n
Emitted when a new connection is made. socket
is an instance of\nnet.Socket
.\n\n
Emitted when the server closes.\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
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
Construct a new socket object.\n\n
\noptions
is an object with the following defaults:\n\n
{ fd: null\n type: null\n allowHalfOpen: false\n}
\nfd
allows you to specify the existing file descriptor of socket. type
\nspecified underlying protocol. It can be 'tcp4'
, 'tcp6'
, or 'unix'
.\nAbout allowHalfOpen
, refer to createServer()
and 'end'
event.\n\n
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
Normally this method is not needed, as net.createConnection
opens the\nsocket. Use this only if you are implementing a custom Socket or if a\nSocket is closed and you want to reuse it to connect to another server.\n\n
This function is asynchronous. When the 'connect' event is\nemitted the socket is established. If there is a problem connecting, the\n'connect'
event will not be emitted, the 'error'
event will be emitted with\nthe exception.\n\n
The connectListener
parameter will be added as an listener for the\n'connect' event.\n\n\n
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
Normally this method is not needed, as net.createConnection
opens the\nsocket. Use this only if you are implementing a custom Socket or if a\nSocket is closed and you want to reuse it to connect to another server.\n\n
This function is asynchronous. When the 'connect' event is\nemitted the socket is established. If there is a problem connecting, the\n'connect'
event will not be emitted, the 'error'
event will be emitted with\nthe exception.\n\n
The connectListener
parameter will be added as an listener for the\n'connect' event.\n\n\n
Sets the encoding (either 'ascii'
, 'utf8'
, or 'base64'
) for data that is\nreceived. Defaults to null
.\n\n
This function has been removed in v0.3. It used to upgrade the connection to\nSSL/TLS. See the TLS section for the new API.\n\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "socket.write(data, [encoding], [callback])", "type": "method", "name": "write", "desc": "Sends data on the socket. The second parameter specifies the encoding in the\ncase of a string--it defaults to UTF8 encoding.\n\n
\nReturns true
if the entire data was flushed successfully to the kernel\nbuffer. Returns false
if all or part of the data was queued in user memory.\n'drain'
will be emitted when the buffer is again free.\n\n
The optional callback
parameter will be executed when the data is finally\nwritten out - this may not be immediately.\n\n
Half-closes the socket. i.e., it sends a FIN packet. It is possible the\nserver will still send some data.\n\n
\nIf data
is specified, it is equivalent to calling\nsocket.write(data, encoding)
followed by socket.end()
.\n\n
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
Resumes reading after a call to pause()
.\n\n
Sets the socket to timeout after timeout
milliseconds of inactivity on\nthe socket. By default net.Socket
do not have a timeout.\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
If timeout
is 0, then the existing idle timeout is disabled.\n\n
The optional callback
parameter will be added as a one time listener for the\n'timeout'
event.\n\n
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
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
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
Returns the bound address and port of the socket as reported by the operating\nsystem. Returns an object with two properties, e.g.\n{"address":"192.168.57.1", "port":62053}
\n\n
net.Socket
has the property that socket.write()
always works. This is to\nhelp users get up and running quickly. The computer cannot always keep up\nwith the amount of data that is written to a socket - the network connection\nsimply might be too slow. Node 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
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
\nUsers who experience large or growing bufferSize
should attempt to\n"throttle" the data flows in their program with pause()
and resume()
.\n\n\n
The string representation of the remote IP address. For example,\n'74.125.127.100'
or '2001:4860:a005::68'
.\n\n
The numeric representation of the remote port. For example,\n80
or 21
.\n\n
The amount of received bytes.\n\n
\n" }, { "textRaw": "socket.bytesWritten", "name": "bytesWritten", "desc": "The amount of bytes sent.\n\n\n
\nnet.Socket
instances are EventEmitters with the following events:\n\n
Emitted when a socket connection is successfully established.\nSee connect()
.\n\n
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\ninformation.)\n\n
Note that the data will be lost if there is no listener when a Socket
\nemits a 'data'
event.\n\n
Emitted when the other end of the socket sends a FIN packet.\n\n
\nBy default (allowHalfOpen == false
) the socket will destroy its file\ndescriptor once it has written out its pending write queue. However, by\nsetting allowHalfOpen == true
the socket will not automatically end()
\nits side allowing the user to write arbitrary amounts of data, with the\ncaveat that the user is required to end()
their side now.\n\n\n
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
\nSee also: socket.setTimeout()
\n\n\n
Emitted when the write buffer becomes empty. Can be used to throttle uploads.\n\n
\nSee also: the return values of socket.write()
\n\n
Emitted when an error occurs. The 'close'
event will be called directly\nfollowing this event.\n\n
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
Datagram sockets are available through require('dgram')
.\n\n
Creates a datagram Socket of the specified types. Valid types are udp4
\nand udp6
.\n\n
Takes an optional callback which is added as a listener for message
events.\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
The dgram Socket class encapsulates the datagram functionality. It\nshould be created via dgram.createSocket(type, [callback])
.\n\n
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
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
Emitted when an error occurs.\n\n
\n" } ], "methods": [ { "textRaw": "dgram.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 IP ", "name": "address", "desc": "String. destination IP" }, { "textRaw": "`callback` Function. Callback when message is done being delivered. Optional. ", "name": "callback", "desc": "Function. Callback when message is done being delivered. 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 IP address must be specified. A string\nmay be supplied for the address
parameter, and it will be resolved with DNS. An\noptional callback may be specified to detect any DNS errors and when buf
may be\nre-used. Note that DNS lookups will delay the time that a send takes place, at\nleast until the next tick. The only way to know for sure that a send has taken place\nis to use the callback.\n\n
If the socket has not been previously bound with a call to bind
, it's\nassigned a random port number and bound to the "all interfaces" address\n(0.0.0.0 for udp4
sockets, ::0 for udp6
sockets).\n\n
Example of sending a UDP packet to a random port on localhost
;\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});
\nA Note about UDP datagram size\n\n
\nThe maximum size of an IPv4/v6
datagram depends on the MTU
(Maximum Transmission Unit)\nand on the Payload Length
field size.\n\n
The Payload Length
field is 16 bits
wide, which means that a normal payload\ncannot be larger than 64K octets including internet header and data\n(65,507 bytes = 65,535 − 8 bytes UDP header − 20 bytes IP header);\nthis is generally true for loopback interfaces, but such long datagrams\nare impractical for most hosts and networks.
The MTU
is the largest size a given link layer technology can support for datagrams.\nFor any link, IPv4
mandates a minimum MTU
of 68
octets, while the recommended MTU
\nfor IPv4 is 576
(typically recommended as the MTU
for dial-up type applications),\nwhether they arrive whole or in fragments.
For IPv6
, the minimum MTU
is 1280
octets, however, the mandatory minimum\nfragment reassembly buffer size is 1500
octets.\nThe value of 68
octets is very small, since most current link layer technologies have\na minimum MTU
of 1500
(like Ethernet).
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
For UDP sockets, listen for datagrams on a named port
and optional address
. If\naddress
is not specified, the OS will try to listen on all addresses.\n\n
Example of a UDP server listening on port 41234:\n\n
\nvar dgram = require("dgram");\n\nvar server = dgram.createSocket("udp4");\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": "dgram.close()",
"type": "method",
"name": "close",
"desc": "Close the underlying socket and stop listening for data on it.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "dgram.address()", "type": "method", "name": "address", "desc": "Returns an object containing the address information for a socket. For UDP sockets,\nthis object will contain address
and port
.\n\n
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
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
The argument to setTTL()
is a number of hops between 1 and 255. The default on most\nsystems is 64.\n\n
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
The argument to setMulticastTTL()
is a number of hops between 0 and 255. The default on most\nsystems is 64.\n\n
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
Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP
socket option.\n\n
If multicastInterface
is not specified, the OS will try to add membership to all valid\ninterfaces.\n\n
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
If multicastInterface
is not specified, the OS will try to drop membership to all valid\ninterfaces.\n\n
Use require('dns')
to access this module. All methods in the dns module\nuse C-Ares except for dns.lookup
which uses getaddrinfo(3)
in a thread\npool. C-Ares is much faster than getaddrinfo
but the system resolver is\nmore constant with how other programs operate. When a user does\nnet.connect(80, 'google.com')
or http.get({ host: 'google.com' })
the\ndns.lookup
method is used. Users who need to do a large number of look ups\nquickly should use the methods that go through C-Ares.\n\n
Here is an example which resolves 'www.google.com'
then reverse\nresolves the IP addresses which are returned.\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 console.log('reverse for ' + a + ' failed: ' +\n err.message);\n } else {\n console.log('reverse for ' + a + ': ' +\n JSON.stringify(domains));\n }\n });\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
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
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
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
On error, err
would be an instanceof Error
object, where err.errno
is\none of the error codes listed below and err.message
is a string describing\nthe error in English.\n\n\n
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
The same as dns.resolve4()
except for IPv6 queries (an AAAA
query).\n\n\n
The same as dns.resolve()
, but only for mail exchange queries (MX
records).\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
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
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
Reverse resolves an ip address to an array of domain names.\n\n
\nThe callback has arguments (err, domains)
.\n\n
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
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
If there an an error, err
will be non-null and an instanceof the Error\nobject.\n\n
Each DNS query can return an error code.\n\n
\ndns.TEMPFAIL
: timeout, SERVFAIL or similar.dns.PROTOCOL
: got garbled reply.dns.NXDOMAIN
: domain does not exists.dns.NODATA
: domain exists but no data of reqd type.dns.NOMEM
: out of memory while processing.dns.BADQUERY
: the query is malformed.To use the HTTP server and client one must require('http')
.\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
\nHTTP 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': '*/*' }
\nKeys are lowercased. Values are not modified.\n\n
\nIn 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", "methods": [ { "textRaw": "http.createServer([requestListener])", "type": "method", "name": "createServer", "desc": "Returns a new web server object.\n\n
\nThe requestListener
is a function which is automatically\nadded to the 'request'
event.\n\n
Node maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests. options
align\nwith url.parse().\n\n
Options:\n\n
\nhost
: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'
.hostname
: To support url.parse()
hostname
is preferred over host
port
: Port of remote server. Defaults to 80.socketPath
: Unix Domain Socket (use one of host:port or socketPath)method
: A string specifying the HTTP request method. Defaults to 'GET'
.path
: Request path. Defaults to '/'
. Should include query string if any.\nE.G. '/index.html?page=12'
headers
: An object containing request headers.auth
: Basic authentication i.e. 'user:password'
to compute an\nAuthorization header.agent
: Controls Agent behavior. When an Agent is used\nrequest will default to Connection: keep-alive
. Possible values:undefined
(default): use global Agent for this host\nand port.Agent
object: explicitly use the passed in Agent
.false
: opts out of connection pooling with an Agent, defaults request to\nConnection: close
.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
Example:\n\n
\nvar options = {\n host: '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();
\nNote that in the example req.end()
was called. With http.request()
one\nmust always call req.end()
to signify that you're done with the request -\neven if there is no data being written to the request body.\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
There are a few special headers that should be noted.\n\n
\nSending a 'Connection: keep-alive' will notify Node that the connection to\nthe server should be persisted until the next request.
\nSending a 'Content-length' header will disable the default chunked encoding.
\nSending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', you should both set a timeout\nand listen for the continue
event. See RFC2616 Section 8.2.3 for more\ninformation.
Sending an Authorization header will override using the auth
option\nto compute basic authentication.
Since most requests are GET requests without bodies, Node provides this\nconvenience method. The only difference between this method and http.request()
is\nthat it sets the method to GET and calls req.end()
automatically.\n\n
Example:\n\n
\nvar options = {\n host: 'www.google.com',\n port: 80,\n path: '/index.html'\n};\n\nhttp.get(options, 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"
}
]
}
]
}
],
"classes": [
{
"textRaw": "Class: http.Server",
"type": "class",
"name": "http.Server",
"desc": "This is an EventEmitter
with the following events:\n\n
function (request, response) { }
\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.ServerRequest
and response
is\n an instance of http.ServerResponse
\n\n
function (socket) { }
\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. The\n socket
can also be accessed at request.connection
.\n\n
function () { }
\n\n
Emitted when the server closes.\n\n
\n", "params": [] }, { "textRaw": "Event: 'checkContinue'", "type": "event", "name": "checkContinue", "desc": "function (request, response) { }
\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
\nHandling 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
Note that when this event is emitted and handled, the request
event will\nnot be emitted.\n\n
function (request, socket, head) { }
\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
\nrequest
is the arguments for the http request, as it is in the request event.socket
is the network socket between the server and client.head
is an instance of Buffer, the first packet of the upgraded stream, this may be empty.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
function (exception) { }
\n\n
If a client connection emits an 'error' event - it will forwarded here.\n\n
\n", "params": [] } ], "methods": [ { "textRaw": "server.listen(port, [hostname], [callback])", "type": "method", "name": "listen", "desc": "Begin accepting connections on the specified port and hostname. If the\nhostname is omitted, the server will accept connections directed to any\nIPv4 address (INADDR_ANY
).\n\n
To listen to a unix socket, supply a filename instead of port and hostname.\n\n
\nThis 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
Start a UNIX socket server listening for connections on the given path
.\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
Stops the server from accepting new connections.\nSee net.Server.close().\n\n\n
\n", "signatures": [ { "params": [] } ] } ] }, { "textRaw": "Class: http.ServerRequest", "type": "class", "name": "http.ServerRequest", "desc": "This object is created internally by a HTTP server -- not by\nthe user -- and passed as the first argument to a 'request'
listener.\n\n
The request implements the Readable Stream\ninterface. This is an EventEmitter
with the following events:\n\n
function (chunk) { }
\n\n
Emitted when a piece of the message body is received. The chunk is a string if\nan encoding has been set with request.setEncoding()
, otherwise it's a\nBuffer.\n\n
Note that the data will be lost if there is no listener when a\nServerRequest
emits a 'data'
event.\n\n
function () { }
\n\n
Emitted exactly once for each request. After that, no more 'data'
events\nwill be emitted on the request.\n\n
function () { }
\n\n
Indicates that the underlaying connection was terminated before\nresponse.end()
was called or able to flush.\n\n
Just like 'end'
, this event occurs only once per request, and no more 'data'
\nevents will fire afterwards.\n\n
Note: 'close'
can fire after 'end'
, but not vice versa.\n\n
The request method as a string. Read only. Example:\n'GET'
, 'DELETE'
.\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
\nGET /status?name=ryan HTTP/1.1\\r\\n\nAccept: text/plain\\r\\n\n\\r\\n
\nThen request.url
will be:\n\n
'/status?name=ryan'
\nIf you would like to parse the URL into its parts, you can use\nrequire('url').parse(request.url)
. Example:\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' }
\nIf 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
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": "request.headers",
"name": "headers",
"desc": "Read only.\n\n
\n" }, { "textRaw": "request.trailers", "name": "trailers", "desc": "Read only; HTTP trailers (if present). Only populated after the 'end' event.\n\n
\n" }, { "textRaw": "request.httpVersion", "name": "httpVersion", "desc": "The HTTP protocol version as a string. Read only. Examples:\n'1.1'
, '1.0'
.\nAlso request.httpVersionMajor
is the first integer and\nrequest.httpVersionMinor
is the second.\n\n\n
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
\n" } ], "methods": [ { "textRaw": "request.setEncoding([encoding])", "type": "method", "name": "setEncoding", "desc": "Set the encoding for the request body. Either 'utf8'
or 'binary'
. Defaults\nto null
, which means that the 'data'
event will emit a Buffer
object..\n\n\n
Pauses request from emitting events. Useful to throttle back an upload.\n\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "request.resume()", "type": "method", "name": "resume", "desc": "Resumes a paused request.\n\n
\n", "signatures": [ { "params": [] } ] } ] }, { "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
The response implements the Writable Stream\ninterface. This is an EventEmitter
with the following events:\n\n
function () { }
\n\n
Indicates that the underlaying connection was terminated before\nresponse.end()
was called or able to flush.\n\n
Sends a HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the checkContinue event on\nServer
.\n\n
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
Example:\n\n
\nvar body = 'hello world';\nresponse.writeHead(200, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain' });
\nThis method must only be called once on a message and it must\nbe called before response.end()
is called.\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
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
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
\nExample:\n\n
\nresponse.setHeader("Content-Type", "text/html");
\nor\n\n
\nresponse.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
\nExample:\n\n
\nvar 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
\nExample:\n\n
\nresponse.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, it will\nswitch to implicit header mode and flush the implicit headers.\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
\nchunk
can be a string or a buffer. If chunk
is a string,\nthe second parameter specifies how to encode it into a byte stream.\nBy default the encoding
is 'utf8'
.\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
\nThe first time response.write()
is called, it will send the buffered\nheader information and the first body to the client. The second time\nresponse.write()
is called, Node 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
This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.\n\n
\nTrailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g., if the request was HTTP/1.0), they will\nbe silently discarded.\n\n
\nNote that HTTP requires the Trailer
header to be sent if you intend to\nemit trailers, with a list of the header fields in its value. E.g.,\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\nhas been sent; that server should consider this message complete.\nThe method, response.end()
, MUST be called on each\nresponse.\n\n
If data
is specified, it is equivalent to calling response.write(data, encoding)
\nfollowed by response.end()
.\n\n\n
When using implicit headers (not calling response.writeHead()
explicitly), this property\ncontrols the status code that will be send to the client when the headers get\nflushed.\n\n
Example:\n\n
\nresponse.statusCode = 404;
\nAfter response header was sent to the client, this property indicates the\nstatus code which was sent out.\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
\nPreviously, a single agent instance help the pool for single host+port. The\ncurrent implementation now holds sockets for any number of hosts.\n\n
\nThe 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
\nSockets 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
\nhttp.get(options, function(res) {\n // Do stuff\n}).on("socket", function (socket) {\n socket.emit("agentRemove");\n});
\nAlternatively, you could just opt out of pooling entirely using agent:false
:\n\n
http.get({host:'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 host.\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
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.ClientResponse
.\n\n
During the 'response'
event, one can add listeners to the\nresponse object; particularly to listen for the 'data'
event. Note that\nthe 'response'
event is called before any part of the response body is received,\nso there is no need to worry about racing to catch the first part of the\nbody. As long as a listener for 'data'
is added during the 'response'
\nevent, the entire body will be caught.\n\n\n
// Good\nrequest.on('response', function (response) {\n response.on('data', function (chunk) {\n console.log('BODY: ' + chunk);\n });\n});\n\n// Bad - misses all or part of the body\nrequest.on('response', function (response) {\n setTimeout(function () {\n response.on('data', function (chunk) {\n console.log('BODY: ' + chunk);\n });\n }, 10);\n});
\nNote: Node does not check whether Content-Length and the length of the body\nwhich has been transmitted are equal or not.\n\n
\nThe request implements the Writable Stream\ninterface. This is an EventEmitter
with the following events:\n\n
function (response) { }
\n\n
Emitted when a response is received to this request. This event is emitted only once. The\nresponse
argument will be an instance of http.ClientResponse
.\n\n
Options:\n\n
\nhost
: A domain name or IP address of the server to issue the request to.port
: Port of remote server.socketPath
: Unix Domain Socket (use one of host:port or socketPath)function (socket) { }
\n\n
Emitted after a socket is assigned to this request.\n\n
\n", "params": [] }, { "textRaw": "Event: 'upgrade'", "type": "event", "name": "upgrade", "desc": "function (response, socket, head) { }
\n\n
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
\nA client server pair that show you how to listen for the upgrade
event using http.getAgent
:\n\n
var http = require('http');\nvar net = require('net');\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, upgradeHead) {\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\\r\\n');\n\n socket.ondata = function(data, start, end) {\n socket.write(data.toString('utf8', start, end), 'utf8'); // echo back\n };\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 host: '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
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
The chunk
argument should be a buffer or a string.\n\n
The encoding
argument is optional and only applies when chunk
is a string.\nDefaults to 'utf8'
.\n\n\n
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
If data
is specified, it is equivalent to calling\nrequest.write(data, encoding)
followed by request.end()
.\n\n
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 \nsocket.setTimeout(timeout, [callback])\nwill 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 \nsocket.setNoDelay(noDelay)\nwill 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 \nsocket.setKeepAlive(enable, [initialDelay])\nwill be called.\n\n
\n", "signatures": [ { "params": [ { "name": "enable", "optional": true }, { "name": "initialDelay", "optional": true } ] } ] } ] } ], "properties": [ { "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.ClientResponse", "name": "ClientResponse", "desc": "This object is created when making a request with http.request()
. It is\npassed to the 'response'
event of the request object.\n\n
The response implements the Readable Stream\ninterface. This is an EventEmitter
with the following events:\n\n\n
function (chunk) { }
\n\n
Emitted when a piece of the message body is received.\n\n
\nNote that the data will be lost if there is no listener when a\nClientResponse
emits a 'data'
event.\n\n\n
function () { }
\n\n
Emitted exactly once for each message. No arguments. After\nemitted no other events will be emitted on the response.\n\n
\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "function (err) { }
\n\n
Indicates that the underlaying connection was terminated before\nend
event was emitted.\nSee http.ServerRequest's 'close'
event for more\ninformation.\n\n
The 3-digit HTTP response status code. E.G. 404
.\n\n
The HTTP version of the connected-to server. Probably either\n'1.1'
or '1.0'
.\nAlso response.httpVersionMajor
is the first integer and\nresponse.httpVersionMinor
is the second.\n\n
The response headers object.\n\n
\n" }, { "textRaw": "response.trailers", "name": "trailers", "desc": "The response trailers object. Only populated after the 'end' event.\n\n
\n" } ], "methods": [ { "textRaw": "response.setEncoding([encoding])", "type": "method", "name": "setEncoding", "desc": "Set the encoding for the response body. Either 'utf8'
, 'ascii'
, or\n'base64'
. Defaults to null
, which means that the 'data'
event will emit\na Buffer
object.\n\n
Pauses response from emitting events. Useful to throttle back a download.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "response.resume()", "type": "method", "name": "resume", "desc": "Resumes a paused response.\n\n
\n", "signatures": [ { "params": [] } ] } ] } ], "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
An Agent object for HTTPS similar to http.Agent.\nSee https.request() for 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\ntls.createServer()
. The requestListener
is a function which is\nautomatically added to the 'request'
event.\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);
\nOr\n\n
\nvar 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",
"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.\nAll options from http.request() are valid.\n\n
\nExample:\n\n
\nvar https = require('https');\n\nvar options = {\n host: '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});
\nThe options argument has the following options\n\n
\n'localhost'
.'/'
.method: HTTP request method. Default 'GET'
.
host
: A domain name or IP address of the server to issue the request to.\nDefaults to 'localhost'
.
hostname
: To support url.parse()
hostname
is preferred over host
port
: Port of remote server. Defaults to 443.method
: A string specifying the HTTP request method. Defaults to 'GET'
.path
: Request path. Defaults to '/'
. Should include query string if any.\nE.G. '/index.html?page=12'
headers
: An object containing request headers.auth
: Basic authentication i.e. 'user:password'
to compute an\nAuthorization header.agent
: Controls Agent behavior. When an Agent is\nused request will default to Connection: keep-alive
. Possible values:undefined
(default): use globalAgent for this\nhost and port.Agent
object: explicitly use the passed in Agent
.false
: opts out of connection pooling with an Agent, defaults request to\nConnection: close
.The following options from tls.connect() can also be\nspecified. However, a globalAgent silently ignores these.\n\n
\npfx
: Certificate, Private key and CA certificates to use for SSL. Default null
.key
: Private key to use for SSL. Default null
.passphrase
: A string of passphrase for the private key or pfx. Default null
.cert
: Public x509 certificate to use. Default null
.ca
: An authority certificate or array of authority certificates to check\nthe remote host against.In order to specify these options, use a custom Agent
.\n\n
Example:\n\n
\nvar options = {\n host: '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}
\nOr does not use an Agent
.\n\n
Example:\n\n
\nvar options = {\n host: '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
Example:\n\n
\nvar https = require('https');\n\nhttps.get({ host: 'encrypted.google.com', path: '/' }, 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 which is used as the default\nfor 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
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
href
: The full URL that was originally parsed. Both the protocol and host are lowercased.
Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
protocol
: The request protocol, lowercased.
Example: 'http:'
host
: The full lowercased host portion of the URL, including port\ninformation.
Example: 'host.com:8080'
auth
: The authentication information portion of a URL.
Example: 'user:pass'
hostname
: Just the lowercased hostname portion of the host.
Example: 'host.com'
port
: The port number portion of the host.
Example: '8080'
pathname
: The path section of the URL, that comes after the host and\nbefore the query, including the initial slash if present.
Example: '/p/a/t/h'
search
: The 'query string' portion of the URL, including the leading\nquestion mark.
Example: '?query=string'
path
: Concatenation of pathname
and search
.
Example: '/p/a/t/h?query=string'
query
: Either the 'params' portion of the query string, or a\nquerystring-parsed object.
Example: 'query=string'
or {'query':'string'}
hash
: The 'fragment' portion of the URL including the pound-sign.
Example: '#hash'
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
\nPass true
as the second argument to also parse\nthe query string using the querystring
module.\nDefaults to false
.\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
Take a parsed URL object, and return a formatted URL string.\n\n
\nhref
will be ignored.protocol
is treated the same with or without the trailing :
(colon).http
, https
, ftp
, gopher
, file
will be\npostfixed with ://
(colon-slash-slash).mailto
, xmpp
, aim
, sftp
, foo
, etc will\nbe postfixed with :
(colon)auth
will be used if present.hostname
will only be used if host
is absent.port
will only be used if host
is absent.host
will be used in place of auth
, hostname
, and port
pathname
is treated the same with or without the leading /
(slash)search
will be used in place of query
query
(object; see querystring
) will only be used if search
is absent.search
is treated the same with or without the leading ?
(question mark)hash
is treated the same with or without the leading #
(pound sign, anchor)Take a base URL, and a href URL, and resolve them as a browser would for\nan anchor tag.\n\n
\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
Example:\n\n
\nquerystring.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])",
"type": "method",
"name": "parse",
"desc": "Deserialize a query string to an object.\nOptionally override the default separator ('&'
) and assignment ('='
)\ncharacters.\n\n
Example:\n\n
\nquerystring.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
}
]
}
]
}
],
"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
The unescape function used by querystring.parse
,\nprovided so that it could be overridden if necessary.\n\n
To use this module, do require('readline')
. Readline allows reading of a\nstream (such as STDIN) on a line-by-line basis.\n\n
Note that once you've invoked this module, your node program will not\nterminate until you've closed the interface, and the STDIN stream. Here's how\nto allow your program to gracefully terminate:\n\n
\nvar rl = require('readline');\n\nvar i = rl.createInterface(process.stdin, process.stdout, null);\ni.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.");\n\n // These two lines together allow the program to terminate. Without\n // them, it would run forever.\n i.close();\n process.stdin.destroy();\n});
\n",
"methods": [
{
"textRaw": "rl.createInterface(input, output, completer)",
"type": "method",
"name": "createInterface",
"desc": "Takes two streams and creates a readline interface. The completer
function\nis used for autocompletion. When given a substring, it returns [[substr1,\nsubstr2, ...], originalsubstring]
.\n\n
Also completer
can be run in async mode if it accepts two arguments:\n\n
function completer(linePartial, callback) {\n callback(null, [['123'], linePartial]);\n }\n\n
\ncreateInterface
is commonly used with process.stdin
and\nprocess.stdout
in order to accept user input:\n\n
var readline = require('readline'),\n rl = readline.createInterface(process.stdin, process.stdout);
\n",
"signatures": [
{
"params": [
{
"name": "input"
},
{
"name": "output"
},
{
"name": "completer"
}
]
}
]
}
],
"classes": [
{
"textRaw": "Class: Interface",
"type": "class",
"name": "Interface",
"desc": "The class that represents a readline interface with a stdin and stdout\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
Readies readline for input from the user, putting the current setPrompt
\noptions on a new line, giving the user a new spot to write.\n\n
Prepends the prompt with query
and invokes callback
with the user's\nresponse. Displays the query to the user, and then invokes callback
with the\nuser's response after it has been typed.\n\n
Example usage:\n\n
\ninterface.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.close()",
"type": "method",
"name": "close",
"desc": "Closes tty.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.pause()", "type": "method", "name": "pause", "desc": "Pauses tty.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.resume()", "type": "method", "name": "resume", "desc": "Resumes tty.\n\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "rl.write()", "type": "method", "name": "write", "desc": "Writes to tty.\n\n
\n", "signatures": [ { "params": [] } ] } ], "events": [ { "textRaw": "Event: 'line'", "type": "event", "name": "line", "desc": "function (line) {}
\n\n
Emitted whenever the in
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
Example of listening for line
:\n\n
rl.on('line', function (cmd) {\n console.log('You just typed: '+cmd);\n});
\n",
"params": []
},
{
"textRaw": "Event: 'close'",
"type": "event",
"name": "close",
"desc": "function () {}
\n\n
Emitted whenever the in
stream receives a ^C
or ^D
, respectively known\nas SIGINT
and EOT
. This is a good way to know the user is finished using\nyour program.\n\n
Example of listening for close
, and exiting the program afterward:\n\n
rl.on('close', function() {\n console.log('goodbye!');\n process.exit(0);\n});
\nHere's an example of how to use all these together to craft a tiny command\nline interface:\n\n
\nvar readline = require('readline'),\n rl = readline.createInterface(process.stdin, process.stdout),\n prefix = 'OHAI> ';\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.setPrompt(prefix, prefix.length);\n rl.prompt();\n}).on('close', function() {\n console.log('Have a great day!');\n process.exit(0);\n});\nconsole.log(prefix + 'Good to see you. Try typing stuff.');\nrl.setPrompt(prefix, prefix.length);\nrl.prompt();
\nTake a look at this slightly more complicated\nexample, and\nhttp-console for a real-life use\ncase.\n\n
\n", "params": [] } ] } ], "type": "module", "displayName": "Readline" }, { "textRaw": "REPL", "name": "repl", "desc": "A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily\nincludable in other programs. REPL provides a way to interactively run\nJavaScript and see the results. It can be used for debugging, testing, or\njust trying things out.\n\n
\nBy executing node
without any arguments from the command-line you will be\ndropped into the REPL. It has simplistic emacs line-editing.\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
\nFor advanced line-editors, start node with the environmental variable NODE_NO_READLINE=1
.\nThis will start the REPL in canonical terminal settings which will allow you to use with rlwrap
.\n\n
For example, you could add this to your bashrc file:\n\n
\nalias node="env NODE_NO_READLINE=1 rlwrap node"
\n",
"methods": [
{
"textRaw": "repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined])",
"type": "method",
"name": "start",
"desc": "Starts a REPL with prompt
as the prompt and stream
for all I/O. prompt
\nis optional and defaults to >
. stream
is optional and defaults to\nprocess.stdin
. eval
is optional too and defaults to async wrapper for\neval()
.\n\n
If useGlobal
is set to true, then the repl will use the global object,\ninstead of running scripts in a separate context. Defaults to false
.\n\n
If ignoreUndefined
is set to true, then the repl will not output return value\nof command if it's undefined
. Defaults to false
.\n\n
You can use your own eval
function if it has following signature:\n\n
function eval(cmd, callback) {\n callback(null, result);\n}
\nMultiple 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
\nHere is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:\n\n
\nvar net = require("net"),\n repl = require("repl");\n\nconnections = 0;\n\nrepl.start("node via stdin> ");\n\nnet.createServer(function (socket) {\n connections += 1;\n repl.start("node via Unix socket> ", socket);\n}).listen("/tmp/node-repl-sock");\n\nnet.createServer(function (socket) {\n connections += 1;\n repl.start("node via TCP socket> ", socket);\n}).listen(5001);
\nRunning 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
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
\n", "signatures": [ { "params": [ { "name": "prompt", "optional": true }, { "name": "stream", "optional": true }, { "name": "eval", "optional": true }, { "name": "useGlobal", "optional": true }, { "name": "ignoreUndefined", "optional": true } ] } ] } ], "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
\nThe special variable _
(underscore) contains the result of the last expression.\n\n
> [ "a", "b", "c" ]\n[ 'a', 'b', 'c' ]\n> _.length\n3\n> _ += 1\n4
\nThe 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
// repl_test.js\nvar repl = require("repl"),\n msg = "message";\n\nrepl.start().context.m = msg;
\nThings in the context
object appear as local within the REPL:\n\n
mjr:~$ node repl_test.js\n> m\n'message'
\nThere are a few special REPL commands:\n\n
\n.break
- While inputting a multi-line expression, sometimes you get lost\nor just don't care about completing it. .break
will start over..clear
- Resets the context
object to an empty object and clears any\nmulti-line expression..exit
- Close the I/O stream, which will cause the REPL to exit..help
- Show this list of special commands..save
- Save the current REPL session to a file\n\n.save ./file/to/save.js
\n
.load
- Load a file into the current REPL session.\n\n.load ./file/to/load.js
\n
The following key combinations in the REPL have these special effects:\n\n
\n<ctrl>C
- Similar to the .break
keyword. Terminates the current\ncommand. Press twice on a blank line to forcibly exit.<ctrl>D
- Similar to the .exit
keyword.You can access this module with:\n\n
\nvar vm = require('vm');
\nJavaScript code can be compiled and run immediately or compiled, saved, and run later.\n\n\n
\n", "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
Example of using vm.runInThisContext
and eval
to run the same code:\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
\nvm.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
In case of syntax error in code
, vm.runInThisContext
emits the syntax error to stderr\nand throws an exception.\n\n\n
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
Example: compile and execute code that increments a global variable and sets a new one.\nThese globals are contained in the sandbox.\n\n
\nvar 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' }
\nNote 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
In case of syntax error in code
, vm.runInNewContext
emits the syntax error to stderr\nand throws an exception.\n\n
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
Example: compile and execute code in a existing context.\n\n
\nvar 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' }
\nNote that createContext
will perform a shallow clone of the supplied sandbox object in order to\ninitialise the global object of the freshly constructed context.\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
In case of syntax error in code
, vm.runInContext
emits the syntax error to stderr\nand throws an exception.\n\n
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
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
In case of syntax error in code
, createScript
prints the syntax error to stderr\nand throws an exception.\n\n\n
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
Example of using script.runInThisContext
to compile code once and run it multiple times:\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
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
\nvar 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' }
\nNote 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
Node provides a tri-directional popen(3)
facility through the\nchild_process
module.\n\n
It is possible to stream data through a child's stdin
, stdout
, and\nstderr
in a fully non-blocking way.\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
ChildProcess
is an EventEmitter
.\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
The ChildProcess class is not intended to be used directly. Use the\nspawn()
or fork()
methods to create a Child Process instance.\n\n
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
See waitpid(2)
.\n\n
A Writable Stream
that represents the child process's stdin
.\nClosing this stream via end()
often causes the child process to terminate.\n\n
If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n
\n" }, { "textRaw": "`stdout` {Stream object} ", "name": "stdout", "desc": "A Readable Stream
that represents the child process's stdout
.\n\n
If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n
\n" }, { "textRaw": "`stderr` {Stream object} ", "name": "stderr", "desc": "A Readable Stream
that represents the child process's stderr
.\n\n
If the child stdio streams are shared with the parent, then this will\nnot be set.\n\n
\n" }, { "textRaw": "`pid` {Integer} ", "name": "pid", "desc": "The PID of the child process.\n\n
\nExample:\n\n
\nvar spawn = require('child_process').spawn,\n grep = spawn('grep', ['ssh']);\n\nconsole.log('Spawned child pid: ' + grep.pid);\ngrep.stdin.end();
\n"
}
],
"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
var spawn = require('child_process').spawn,\n grep = spawn('grep', ['ssh']);\n\ngrep.on('exit', 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');
\nNote that while the function is called kill
, the signal delivered to the child\nprocess may not actually kill it. kill
really just sends a signal to a process.\n\n
See kill(2)
\n\n
Send a message (and, optionally, a handle object) to a child process.\n\n
\nSee child_process.fork()
for details.\n\n
Launches a new process with the given command
, with command line arguments in args
.\nIf omitted, args
defaults to an empty Array.\n\n
The third argument is used to specify additional options, which defaults to:\n\n
\n{ cwd: undefined,\n env: process.env\n}
\ncwd
allows you to specify the working directory from which the process is spawned.\nUse env
to specify environment variables that will be visible to the new process.\n\n
Example of running ls -lh /usr
, capturing stdout
, stderr
, and the exit code:\n\n
var util = require('util'),\n 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('exit', function (code) {\n console.log('child process exited with code ' + code);\n});
\nExample: A very elaborate way to run 'ps ax | grep ssh'\n\n
\nvar util = require('util'),\n 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('exit', 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('exit', function (code) {\n if (code !== 0) {\n console.log('grep process exited with code ' + code);\n }\n});
\nExample of checking for failed exec:\n\n
\nvar spawn = require('child_process').spawn,\n child = spawn('bad_command');\n\nchild.stderr.setEncoding('utf8');\nchild.stderr.on('data', function (data) {\n if (/^execvp\\(\\)/.test(data)) {\n console.log('Failed to start child process.');\n }\n});
\nNote that if spawn receives an empty options object, it will result in\nspawning the process with an empty environment rather than using\nprocess.env
. This due to backwards compatibility issues with a deprecated\nAPI.\n\n
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
There are several internal options. In particular stdinStream
,\nstdoutStream
, stderrStream
. They are for INTERNAL USE ONLY. As with all\nundocumented APIs in Node, they should not be used.\n\n
See also: child_process.exec()
and child_process.fork()
\n\n
Runs a command in a shell and buffers the output.\n\n
\nvar util = require('util'),\n 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});
\nThe callback gets the arguments (error, stdout, stderr)
. On success, error
\nwill be null
. On error, error
will be an instance of Error
and err.code
\nwill be the exit code of the child process, and err.signal
will be set to the\nsignal that terminated the process.\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 }
\nIf 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
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
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. The\nchannel is written to with child.send(message, [sendHandle])
and messages\nare received by a 'message'
event on the child.\n\n
For example:\n\n
\nvar 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' });
\nAnd then the child script, 'sub.js'
might look like this:\n\n
process.on('message', function(m) {\n console.log('CHILD got message:', m);\n});\n\nprocess.send({ foo: 'bar' });
\nIn 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
By default the spawned Node process will have the stdin, stdout, stderr\nassociated with the parent's.\n\n
\nThese 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
\nThe sendHandle
option to child.send()
is for sending a handle object to\nanother process. Child will receive the handle as as second argument to the\nmessage
event. Here is an example of sending a handle:\n\n
var server = require('net').createServer();\nvar child = require('child_process').fork(__dirname + '/child.js');\n// Open up the server object and send the handle.\nserver.listen(1337, function() {\n child.send({ server: true }, server._handle);\n});
\nHere is an example of receiving the server handle and sharing it between\nprocesses:\n\n
\nprocess.on('message', function(m, serverHandle) {\n if (serverHandle) {\n var server = require('net').createServer();\n server.listen(serverHandle);\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
Throws an exception that displays the values for actual
and expected
separated by the provided operator.\n\n
Tests if value is a true
value, it is equivalent to assert.equal(true, value, message);
\n\n
Tests shallow, coercive equality with the equal comparison operator ( ==
).\n\n
Tests shallow, coercive non-equality with the not equal comparison operator ( !=
).\n\n
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
Tests strict non-equality, as determined by the strict not equal operator ( !==
)\n\n
Expects block
to throw an error. error
can be constructor, regexp or \nvalidation function.\n\n
Validate instanceof using constructor:\n\n
\nassert.throws(\n function() {\n throw new Error("Wrong value");\n },\n Error\n);
\nValidate error message using RegExp:\n\n
\nassert.throws(\n function() {\n throw new Error("Wrong value");\n },\n /value/\n);
\nCustom error validation:\n\n
\nassert.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, [error], [message])",
"type": "method",
"name": "doesNotThrow",
"desc": "Expects block
not to throw an error, see assert.throws for details.\n\n
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
Use require('tty')
to access this module.\n\n
Example:\n\n
\nvar tty = require('tty');\nprocess.stdin.resume();\ntty.setRawMode(true);\nprocess.stdin.on('keypress', function(char, key) {\n if (key && key.ctrl && key.name == 'c') {\n console.log('graceful exit');\n process.exit()\n }\n});
\n",
"methods": [
{
"textRaw": "tty.isatty(fd)",
"type": "method",
"name": "isatty",
"desc": "Returns true
or false
depending on if the fd
is associated with a\nterminal.\n\n\n
mode
should be true
or false
. This sets the properties of the current\nprocess's stdin fd to act either as a raw device or default.\n\n
You can access this module with:\n\n
\nvar zlib = require('zlib');
\nThis 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
\nCompressing or decompressing a file can be done by piping an\nfs.ReadStream into a zlib stream, then into an fs.WriteStream.\n\n
\nvar 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);
\nCompressing or decompressing data in one step can be done by using\nthe convenience methods.\n\n
\nvar 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});
\nTo use this module in an HTTP client or server, use the\naccept-encoding\non requests, and the\ncontent-encoding\nheader on responses.\n\n
\nNote: 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",
"miscs": [
{
"textRaw": "Constants",
"name": "Constants",
"type": "misc",
"desc": "All of the constants defined in zlib.h are also defined on\nrequire('zlib')
. They are described in more detail in the zlib\ndocumentation. See http://zlib.net/manual.html#Constants\nfor more details.\n\n
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
Each class takes an options object. All options are optional. (The\nconvenience methods use the default settings for all options.)\n\n
\nNote that some options are only\nrelevant when compressing, and are ignored by the decompression classes.\n\n
\nSee the description of deflateInit2
and inflateInit2
at\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
The memory requirements for deflate are (in bytes):\n\n
\n(1 << (windowBits+2)) + (1 << (memLevel+9))
\nthat is: 128K for windowBits=15 + 128K for memLevel = 8\n(default values) plus a few kilobytes for small objects.\n\n
\nFor 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 }
\nOf course this will generally degrade compression (there's no free lunch).\n\n
\nThe memory requirements for inflate are (in bytes)\n\n
\n1 << windowBits
\nthat is, 32K for windowBits=15 (default value) plus a few kilobytes\nfor small objects.\n\n
\nThis is in addition to a single internal output slab buffer of size\nchunkSize
, which defaults to 16K.\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
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
Returns a new Gzip object with an options.\n\n
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createGunzip([options])", "type": "method", "name": "createGunzip", "desc": "Returns a new Gunzip object with an options.\n\n
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflate([options])", "type": "method", "name": "createDeflate", "desc": "Returns a new Deflate object with an options.\n\n
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflate([options])", "type": "method", "name": "createInflate", "desc": "Returns a new Inflate object with an options.\n\n
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createDeflateRaw([options])", "type": "method", "name": "createDeflateRaw", "desc": "Returns a new DeflateRaw object with an options.\n\n
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createInflateRaw([options])", "type": "method", "name": "createInflateRaw", "desc": "Returns a new InflateRaw object with an options.\n\n
\n", "signatures": [ { "params": [ { "name": "options", "optional": true } ] } ] }, { "textRaw": "zlib.createUnzip([options])", "type": "method", "name": "createUnzip", "desc": "Returns a new Unzip object with an options.\n\n\n
\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.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" } ], "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
\nUse require('os')
to access this module.\n\n
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", "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 installed: model, speed (in MHz), and times (an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq).\n\n
\nExample 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": []
}
]
}
],
"type": "module",
"displayName": "os"
},
{
"textRaw": "Cluster",
"name": "cluster",
"stability": 1,
"stabilityText": "Experimental - Drastic changes in future versions",
"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
\nThe cluster module allows you to easily create a network of processes that\nall share server ports.\n\n
\nvar 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('death', function(worker) {\n console.log('worker ' + worker.pid + ' died');\n });\n} else {\n // Worker processes have a http server.\n http.Server(function(req, res) {\n res.writeHead(200);\n res.end("hello world\\n");\n }).listen(8000);\n}
\nRunning node will now share port 8000 between the workers:\n\n
\n% node server.js\nWorker 2438 online\nWorker 2437 online
\nThe difference between cluster.fork()
and child_process.fork()
is simply\nthat cluster allows TCP servers to be shared between workers. cluster.fork
\nis implemented on top of child_process.fork
. The message passing API that\nis available with child_process.fork
is available with cluster
as well.\nAs an example, here is a cluster which keeps count of the number of requests\nin the master process via message passing:\n\n
var cluster = require('cluster');\nvar http = require('http');\nvar numReqs = 0;\n\nif (cluster.isMaster) {\n // Fork workers.\n for (var i = 0; i < 2; i++) {\n var worker = cluster.fork();\n\n worker.on('message', function(msg) {\n if (msg.cmd && msg.cmd == 'notifyRequest') {\n numReqs++;\n }\n });\n }\n\n setInterval(function() {\n console.log("numReqs =", numReqs);\n }, 1000);\n} else {\n // Worker processes have a http server.\n http.Server(function(req, res) {\n res.writeHead(200);\n res.end("hello world\\n");\n // Send message to master process\n process.send({ cmd: 'notifyRequest' });\n }).listen(8000);\n}
\n",
"methods": [
{
"textRaw": "cluster.fork()",
"type": "method",
"name": "fork",
"desc": "Spawn a new worker process. This can only be called from the master process.\n\n
\n", "signatures": [ { "params": [] } ] } ], "properties": [ { "textRaw": "cluster.isMaster", "name": "isMaster", "desc": "Boolean flags to determine if the current process is a master or a worker\nprocess in a cluster. A process isMaster
if process.env.NODE_WORKER_ID
\nis undefined.\n\n
Boolean flags to determine if the current process is a master or a worker\nprocess in a cluster. A process isMaster
if process.env.NODE_WORKER_ID
\nis undefined.\n\n
When any of the workers die the cluster module will emit the 'death' event.\nThis can be used to restart the worker by calling fork()
again.\n\n
cluster.on('death', function(worker) {\n console.log('worker ' + worker.pid + ' died. restart...');\n cluster.fork();\n});
\nDifferent techniques can be used to restart the worker depending on the\napplication.\n\n
\n", "params": [] } ], "type": "module", "displayName": "Cluster" }, { "textRaw": "Appendix 1 - Third Party Modules", "name": "appendix_1_-_third_party_modules", "desc": "There are many third party modules for Node. At the time of writing, August\n2010, the master repository of modules is\nthe wiki page.\n\n
\nThis appendix is intended as a SMALL guide to new-comers to help them\nquickly find what are considered to be quality modules. It is not intended\nto be a complete list. There may be better more complete modules found\nelsewhere.\n\n
\nModule Installer: npm
\nHTTP Middleware: Connect
\nWeb Framework: Express
\nWeb Sockets: Socket.IO
\nHTML Parsing: HTML5
\nSerialization: msgpack
\nScraping: Apricot
\nDebugger: ndb is a CLI debugger\ninspector is a web based\ntool.
\nTesting/TDD/BDD: vows,\nmocha,\nmjsunit.runner
\nPatches to this list are welcome.\n\n
\n", "type": "module", "displayName": "Appendix 1 - Third Party Modules" } ], "stability": 3, "stabilityText": "Stable" }