NodeJS API
NodeJS API
js Manual
&Documentation
Table Of Contents
Synopsis
Global Objects
o global
o process
o require()
o require.resolve()
o require.paths
o __filename
o __dirname
o module
Timers
o setTimeout(callback, delay, [arg], [...])
o clearTimeout(timeoutId)
o setInterval(callback, delay, [arg], [...])
o clearInterval(intervalId)
Modules
o Core Modules
o File Modules
o Loading from `node_modules` Folders
Optimizations to the `node_modules` Lookup Process
o Folders as Modules
o Caching
o All Together...
o Loading from the `require.paths` Folders
Note:** Please Avoid Modifying `require.paths`
Setting `require.paths` to some other value does
nothing.
Putting relative paths in `require.paths` is... weird.
Zero Isolation
Addenda: Package Manager Tips
Addons
process
o Event: 'exit'
o Event: 'uncaughtException'
o Signal Events
o process.stdout
o process.stderr
o process.stdin
o process.argv
o process.execPath
o process.chdir(directory)
o process.cwd()
o process.env
o process.exit(code=0)
o process.getgid()
o process.setgid(id)
o process.getuid()
o process.setuid(id)
o process.version
o process.installPrefix
o process.kill(pid, signal='SIGTERM')
o process.pid
o process.title
o process.platform
o process.memoryUsage()
o process.nextTick(callback)
o process.umask([mask])
util
o util.debug(string)
o util.log(string)
o util.inspect(object, showHidden=false, depth=2)
o util.pump(readableStream, writableStream, [callback])
o util.inherits(constructor, superConstructor)
Events
o events.EventEmitter
emitter.addListener(event, listener)
emitter.on(event, listener)
emitter.once(event, listener)
emitter.removeListener(event, listener)
emitter.removeAllListeners(event)
emitter.setMaxListeners(n)
emitter.listeners(event)
emitter.emit(event, [arg1], [arg2], [...])
Event: 'newListener'
Buffers
o new Buffer(size)
o new Buffer(array)
o new Buffer(str, encoding='utf8')
o buffer.write(string, offset=0, encoding='utf8')
o buffer.toString(encoding, start=0, end=buffer.length)
o buffer[index]
o Buffer.isBuffer(obj)
o Buffer.byteLength(string, encoding='utf8')
o buffer.length
o buffer.copy(targetBuffer, targetStart=0, sourceStart=0,
sourceEnd=buffer.length)
o buffer.slice(start, end=buffer.length)
Streams
Readable Stream
o Event: 'data'
o Event: 'end'
o Event: 'error'
o Event: 'close'
o Event: 'fd'
o stream.readable
o stream.setEncoding(encoding)
o stream.pause()
o stream.resume()
o stream.destroy()
o stream.destroySoon()
o stream.pipe(destination, [options])
Writable Stream
o Event: 'drain'
o Event: 'error'
o Event: 'close'
o Event: 'pipe'
o stream.writable
o stream.write(string, encoding='utf8', [fd])
o stream.write(buffer)
o stream.end()
o stream.end(string, encoding)
o stream.end(buffer)
o stream.destroy()
o stream.destroySoon()
Crypto
o crypto.createCredentials(details)
o crypto.createHash(algorithm)
o hash.update(data)
o hash.digest(encoding='binary')
o crypto.createHmac(algorithm, key)
o hmac.update(data)
o hmac.digest(encoding='binary')
o crypto.createCipher(algorithm, key)
o cipher.update(data, input_encoding='binary',
output_encoding='binary')
o cipher.final(output_encoding='binary')
o crypto.createDecipher(algorithm, key)
o decipher.update(data, input_encoding='binary',
output_encoding='binary')
o decipher.final(output_encoding='binary')
o crypto.createSign(algorithm)
o signer.update(data)
o signer.sign(private_key, output_format='binary')
o crypto.createVerify(algorithm)
o verifier.update(data)
o verifier.verify(cert, signature, signature_format='binary')
TLS (SSL)
o s = tls.connect(port, [host], [options], callback)
o tls.Server
tls.createServer(options, secureConnectionListener)
Event: 'secureConnection'
server.listen(port, [host], [callback])
server.close()
server.maxConnections
server.connections
File System
o fs.rename(path1, path2, [callback])
o fs.renameSync(path1, path2)
o fs.truncate(fd, len, [callback])
o fs.truncateSync(fd, len)
o fs.chmod(path, mode, [callback])
o fs.chmodSync(path, mode)
o fs.stat(path, [callback])
o fs.lstat(path, [callback])
o fs.fstat(fd, [callback])
o fs.statSync(path)
o fs.lstatSync(path)
o fs.fstatSync(fd)
o fs.link(srcpath, dstpath, [callback])
o fs.linkSync(srcpath, dstpath)
o fs.symlink(linkdata, path, [callback])
o fs.symlinkSync(linkdata, path)
o fs.readlink(path, [callback])
o fs.readlinkSync(path)
o fs.realpath(path, [callback])
o fs.realpathSync(path)
o fs.unlink(path, [callback])
o fs.unlinkSync(path)
o fs.rmdir(path, [callback])
o fs.rmdirSync(path)
o fs.mkdir(path, mode, [callback])
o fs.mkdirSync(path, mode)
o fs.readdir(path, [callback])
o fs.readdirSync(path)
o fs.close(fd, [callback])
o fs.closeSync(fd)
o fs.open(path, flags, [mode], [callback])
o fs.openSync(path, flags, [mode])
o fs.write(fd, buffer, offset, length, position, [callback])
o fs.writeSync(fd, buffer, offset, length, position)
o fs.writeSync(fd, str, position, encoding='utf8')
o fs.read(fd, buffer, offset, length, position, [callback])
o fs.readSync(fd, buffer, offset, length, position)
o fs.readSync(fd, length, position, encoding)
o fs.readFile(filename, [encoding], [callback])
o fs.readFileSync(filename, [encoding])
o fs.writeFile(filename, data, encoding='utf8', [callback])
o fs.writeFileSync(filename, data, encoding='utf8')
o fs.watchFile(filename, [options], listener)
o fs.unwatchFile(filename)
fs.Stats
fs.ReadStream
o fs.createReadStream(path, [options])
fs.WriteStream
o Event: 'open'
o fs.createWriteStream(path, [options])
Path
o path.normalize(p)
o path.join([path1], [path2], [...])
o path.resolve([from ...], to)
o path.dirname(p)
o path.basename(p, [ext])
o path.extname(p)
o path.exists(p, [callback])
o path.existsSync(p)
net
o net.createServer([options], [connectionListener])
o net.createConnection(arguments...)
o net.Server
server.listen(port, [host], [callback])
server.listen(path, [callback])
server.listenFD(fd)
server.close()
server.address()
server.maxConnections
server.connections
Event: 'connection'
Event: 'close'
o net.Socket
new net.Socket([options])
socket.connect(port, [host], [callback])
socket.connect(path, [callback])
socket.bufferSize
socket.setEncoding(encoding=null)
socket.setSecure()
socket.write(data, [encoding], [callback])
socket.write(data, [encoding], [fileDescriptor], [callback])
socket.end([data], [encoding])
socket.destroy()
socket.pause()
socket.resume()
socket.setTimeout(timeout, [callback])
socket.setNoDelay(noDelay=true)
socket.setKeepAlive(enable=false, [initialDelay])
socket.remoteAddress
Event: 'connect'
Event: 'data'
Event: 'end'
Event: 'timeout'
Event: 'drain'
Event: 'error'
Event: 'close'
o net.isIP
net.isIP(input)
net.isIPv4(input)
net.isIPv6(input)
DNS
o dns.lookup(domain, family=null, callback)
o dns.resolve(domain, rrtype='A', callback)
o dns.resolve4(domain, callback)
o dns.resolve6(domain, callback)
o dns.resolveMx(domain, callback)
o dns.resolveTxt(domain, callback)
o dns.resolveSrv(domain, callback)
o dns.reverse(ip, callback)
UDP / Datagram Sockets
o Event: 'message'
o Event: 'listening'
o Event: 'close'
o dgram.createSocket(type, [callback])
o dgram.send(buf, offset, length, path, [callback])
o dgram.send(buf, offset, length, port, address, [callback])
o dgram.bind(path)
o dgram.bind(port, [address])
o dgram.close()
o dgram.address()
o dgram.setBroadcast(flag)
o dgram.setTTL(ttl)
o dgram.setMulticastTTL(ttl)
o dgram.setMulticastLoopback(flag)
o dgram.addMembership(multicastAddress, [multicastInterface])
o dgram.dropMembership(multicastAddress, [multicastInterface])
HTTP
http.Server
o Event: 'request'
o Event: 'connection'
o Event: 'close'
o Event: 'request'
o Event: 'checkContinue'
o Event: 'upgrade'
o Event: 'clientError'
o http.createServer(requestListener)
o server.listen(port, [hostname], [callback])
o server.listen(path, [callback])
o server.close()
http.ServerRequest
o Event: 'data'
o Event: 'end'
o request.method
o request.url
o request.headers
o request.trailers
o request.httpVersion
o request.setEncoding(encoding=null)
o request.pause()
o request.resume()
o request.connection
http.ServerResponse
o response.writeContinue()
o response.writeHead(statusCode, [reasonPhrase], [headers])
o response.statusCode
o response.setHeader(name, value)
o response.getHeader(name)
o response.removeHeader(name)
o response.write(chunk, encoding='utf8')
o response.addTrailers(headers)
o response.end([data], [encoding])
http.request(options, callback)
http.get(options, callback)
http.Agent
http.getAgent(host, port)
o Event: 'upgrade'
o Event: 'continue'
o agent.maxSockets
o agent.sockets
o agent.queue
http.ClientRequest
o Event 'response'
o request.write(chunk, encoding='utf8')
o request.end([data], [encoding])
o request.abort()
http.ClientResponse
o Event: 'data'
o Event: 'end'
o response.statusCode
o response.httpVersion
o response.headers
o response.trailers
o response.setEncoding(encoding=null)
o response.pause()
o response.resume()
HTTPS
https.Server
https.createServer
https.request(options, callback)
https.get(options, callback)
URL
o url.parse(urlStr, parseQueryString=false)
o url.format(urlObj)
o url.resolve(from, to)
Query String
o querystring.stringify(obj, sep='&', eq='=')
o querystring.parse(str, sep='&', eq='=')
o querystring.escape
o querystring.unescape
REPL
o repl.start(prompt='> ', stream=process.stdin)
o REPL Features
Child Processes
o Event: 'exit'
o child.stdin
o child.stdout
o child.stderr
o child.pid
o child_process.spawn(command, args=[], [options])
o child_process.exec(command, [options], callback)
o child.kill(signal='SIGTERM')
Assert
o assert.fail(actual, expected, message, operator)
o assert.ok(value, [message])
o assert.equal(actual, expected, [message])
o assert.notEqual(actual, expected, [message])
o assert.deepEqual(actual, expected, [message])
o assert.notDeepEqual(actual, expected, [message])
o assert.strictEqual(actual, expected, [message])
o assert.notStrictEqual(actual, expected, [message])
o assert.throws(block, [error], [message])
o assert.doesNotThrow(block, [error], [message])
o assert.ifError(value)
TTY
o tty.open(path, args=[])
o tty.isatty(fd)
o tty.setRawMode(mode)
o tty.setWindowSize(fd, row, col)
o tty.getWindowSize(fd)
os Module
o os.hostname()
o os.type()
o os.release()
o os.uptime()
o os.loadavg()
o os.totalmem()
o os.freemem()
o os.cpus()
Debugger
o Advanced Usage
Appendixes
Synopsis
An example of a web server written with Node which responds with 'Hello World':
Global Objects
These object are available in the global scope and can be accessed from anywhere.
global
The global namespace object.
In browsers, the top-level scope is the global scope. That means that in browsers
if you're in the global scope var something will define a global variable. In Node
this is different. The top-level scope is not the global scope; var
something inside a Node module will be local to that module.
process
The process object. See the 'process object' section.
require()
To require modules. See the 'Modules' section.
require.resolve()
Use the internal require() machinery to look up the location of a module, but
rather than loading the module, just return the resolved filename.
require.paths
An array of search paths for require(). This array can be modified to add
custom paths.
Example: add a new path to the beginning of the search list
require.paths.unshift('/usr/local/node');
__filename
The filename of the script being executed. This is the absolute path, and not
necessarily the same filename passed in as a command line argument.
console.log(__filename);
// /Users/mjr/example.js
__dirname
The dirname of the script being executed.
console.log(__dirname);
// /Users/mjr
module
A reference to the current module. In particular module.exports is the same as
the exports object. Seesrc/node.js for more information.
Timers
clearTimeout(timeoutId)
Prevents a timeout from triggering.
clearInterval(intervalId)
Stops a interval from triggering.
Modules
Node uses the CommonJS module system.
Node has a simple module loading system. In Node, files and modules are in
one-to-one correspondence. As an example, foo.js loads the
module circle.js in the same directory.
The contents of foo.js:
var PI = Math.PI;
Core Modules
Node has several modules compiled into the binary. These modules are described
in greater detail elsewhere in this documentation.
The core modules are defined in node's source in the lib/ folder.
Core modules are always preferentially loaded if their identifier is passed
to require(). For instance,require('http') will always return the built in
HTTP module, even if there is a file by that name.
File Modules
If the exact filename is not found, then node will attempt to load the required
filename with the added extension of .js, and then .node.
.js files are interpreted as JavaScript text files, and .node files are interpreted
as compiled addon modules loaded with dlopen.
A module prefixed with '/' is an absolute path to the file. For
example, require('/home/marco/foo.js') will load the file
at /home/marco/foo.js.
A module prefixed with './' is relative to the file calling require(). That
is, circle.js must be in the same directory
as foo.js for require('./circle') to find it.
Without a leading '/' or './' to indicate a file, the module is either a "core module"
or is loaded from anode_modules folder.
/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 clash.
Process
When there are many levels of nested dependencies, it is possible for these file
trees to get fairly long. The following optimizations are thus made to the process.
/home/ry/projects/foo/node_modules/bar/node_modules/baz/n
ode_modules/asdf.js
/home/ry/projects/foo/node_modules/bar/node_modules/asdf.
js
/home/ry/projects/foo/node_modules/asdf.js
Folders as Modules
It is convenient to organize programs and libraries into self-contained directories,
and then provide a single entry point to that library. There are three ways in
which a folder may be passed to require() as an argument.
The first is to create a package.json file in the root of the folder, which specifies
a main module. An example package.json file might look like this:
{ "name" : "some-library",
"main" : "./lib/some-library.js" }
If there is no package.json file present in the directory, then node will attempt to
load an index.js orindex.node file out of that directory. For example, if there
was no package.json file in the above example,
thenrequire('./some-library') would attempt to load:
./some-library/index.js
./some-library/index.node
Caching
Modules are cached after the first time they are loaded. This means (among other
things) that every call torequire('foo') will get exactly the same object
returned, if it would resolve to the same file.
All Together...
To get the exact filename that will be loaded when require() is called, use
the require.resolve() function.
Putting together all of the above, here is the high-level algorithm in pseudocode of
what require.resolve does:
require(X)
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with `./` or `/`,
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"
LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text. STOP
2. If X.js is a file, load X.js as JavaScript text. STOP
3. If X.node is a file, load X.node as binary addon. STOP
LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
c. LOAD_AS_FILE(M)
2. LOAD_AS_FILE(X/index)
LOAD_NODE_MODULES(X, START)
1. let DIRS=NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_AS_FILE(DIR/X)
b. LOAD_AS_DIRECTORY(DIR/X)
NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let ROOT = index of first instance of "node_modules" in PARTS, or
0
3. let I = count of PARTS - 1
4. let DIRS = []
5. while I > ROOT,
a. if PARTS[I] = "node_modules" CONTINUE
c. DIR = path join(PARTS[0 .. I] + "node_modules")
b. DIRS = DIRS + DIR
6. return DIRS
[ '/home/micheil/.node_modules',
'/usr/local/lib/node_modules' ]
1: '/home/micheil/.node_modules/bar/baz.js'
2: '/usr/local/lib/node_modules/bar/baz.js'
The require.paths array can be mutated at run time to alter this behavior.
It is set initially from the NODE_PATH environment variable, which is a
colon-delimited list of absolute paths. In the previous example,
the NODE_PATH environment variable might have been set to:
/home/micheil/.node_modules:/usr/local/lib/node_modules
require.paths = [ '/usr/lib/node' ];
All that does is lose the reference to the actual node module lookup paths, and
create a new reference to some other thing that isn't used for anything.
If you do this:
require.paths.push('./lib');
then it does not add the full resolved path to where ./lib is on the filesystem.
Instead, it literally adds './lib', meaning that if you
do require('y.js') in /a/b/x.js, then it'll look in /a/b/lib/y.js. If you
then didrequire('y.js') in /l/m/n/o/p.js, then it'd look
in /l/m/n/o/lib/y.js.
In practice, people have used this as an ad hoc way to bundle dependencies, but
this technique is brittle.
Zero Isolation
There is (by regrettable design), only one require.paths array used by all
modules.
As a result, if one node program comes to rely on this behavior, it may
permanently and subtly alter the behavior of all other node programs in the same
process. As the application stack grows, we tend to assemble functionality, and it
is a problem with those parts interact in ways that are difficult to predict.
When the code in the foo package does require('bar'), it will get the version
that is symlinked into/usr/lib/node/foo/1.2.3/node_modules/bar. Then,
when the code in the bar package callsrequire('quux'), it'll get the version
that is symlinked into /usr/lib/node/bar/4.3.2/node_modules/quux.
Furthermore, to make the module lookup process even more optimal, rather than
putting packages directly in/usr/lib/node, we could put them
in /usr/lib/node_modules/<name>/<version>. Then node will not bother
looking for missing dependencies in /usr/node_modules or /node_modules.
In order to make modules available to the node REPL, it might be useful to also
add the/usr/lib/node_modules folder to the $NODE_PATH environment
variable. Since the module lookups usingnode_modules folders are all relative,
and based on the real path of the files making the calls to require(), the
packages themselves can be anywhere.
Addons
Addons are dynamically linked shared objects. They can provide glue to C and
C++ libraries. The API (at the moment) is rather complex, involving knowledge of
several libraries:
To get started let's make a small Addon which does the following except in C++:
exports.hello = 'world';
#include <v8.h>
This source code needs to be built into hello.node, the binary Addon. To do this
we create a file called wscriptwhich is python code and looks like this:
srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'hello'
obj.source = 'hello.cc'
process
The process object is a global object and can be accessed from anywhere. It is an
instance of EventEmitter.
Event: 'exit'
function () {}
Emitted when the process is about to exit. This is a good hook to perform
constant time checks of the module's state (like for unit tests). The main event
loop will no longer be run after the 'exit' callback finishes, so timers may not be
scheduled.
process.on('exit', function () {
process.nextTick(function () {
console.log('This will not run');
});
console.log('About to exit.');
});
Event: 'uncaughtException'
function (err) { }
Emitted when an exception bubbles all the way back to the event loop. If a
listener is added for this exception, the default action (which is to print a stack
trace and exit) will not occur.
setTimeout(function () {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
Signal Events
function () {}
Emitted when the processes receives a signal. See sigaction(2) for a list of
standard POSIX signal names such as SIGINT, SIGUSR1, etc.
process.on('SIGINT', function () {
console.log('Got SIGINT. Press Control-D to exit.');
});
An easy way to send the SIGINT signal is with Control-C in most terminal
programs.
process.stdout
A Writable Stream to stdout.
Example: the definition of console.log
process.stderr
A writable stream to stderr. Writes on this stream are blocking.
process.stdin
A Readable Stream for stdin. The stdin stream is paused by default, so one must
callprocess.stdin.resume() to read from it.
Example of opening standard input and listening for both events:
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('end', function () {
process.stdout.write('end');
});
process.argv
An array containing the command line arguments. The first element will be 'node',
the second element will be the name of the JavaScript file. The next elements will
be any additional command line arguments.
// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
});
process.execPath
This is the absolute pathname of the executable that started the process.
Example:
/usr/local/bin/node
process.chdir(directory)
Changes the current working directory of the process or throws an exception if
that fails.
process.cwd()
Returns the current working directory of the process.
process.env
An object containing the user environment. See environ(7).
process.exit(code=0)
Ends the process with the specified code. If omitted, exit uses the 'success'
code 0.
To exit with a 'failure' code:
process.exit(1);
The shell that executed node should see the exit code as 1.
process.getgid()
Gets the group identity of the process. (See getgid(2).) This is the numerical
group id, not the group name.
console.log('Current gid: ' + process.getgid());
process.setgid(id)
Sets the group identity of the process. (See setgid(2).) This accepts either a
numerical ID or a groupname string. If a groupname is specified, this method
blocks while resolving it to a numerical ID.
process.getuid()
Gets the user identity of the process. (See getuid(2).) This is the numerical userid,
not the username.
process.setuid(id)
Sets the user identity of the process. (See setuid(2).) This accepts either a
numerical ID or a username string. If a username is specified, this method blocks
while resolving it to a numerical ID.
console.log('Current uid: ' + process.getuid());
try {
process.setuid(501);
console.log('New uid: ' + process.getuid());
}
catch (err) {
console.log('Failed to set uid: ' + err);
}
process.version
A compiled-in property that exposes NODE_VERSION.
process.installPrefix
A compiled-in property that exposes NODE_PREFIX.
process.kill(pid, signal='SIGTERM')
Send a signal to a process. pid is the process id and signal is the string
describing the signal to send. Signal names are strings like 'SIGINT' or 'SIGUSR1'.
If omitted, the signal will be 'SIGTERM'. See kill(2) for more information.
Note that just because the name of this function is process.kill, it is really just
a signal sender, like the killsystem call. The signal sent may do something other
than kill the target process.
Example of sending a signal to yourself:
process.on('SIGHUP', function () {
console.log('Got SIGHUP signal.');
});
setTimeout(function () {
console.log('Exiting.');
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP');
process.pid
The PID of the process.
process.title
Getter/setter to set what is displayed in 'ps'.
process.platform
What platform you're running on. 'linux2', 'darwin', etc.
process.memoryUsage()
Returns an object describing the memory usage of the Node process.
console.log(util.inspect(process.memoryUsage()));
{ rss: 4935680,
vsize: 41893888,
heapTotal: 1826816,
heapUsed: 650472 }
process.nextTick(callback)
On the next loop around the event loop call this callback. This is not a simple alias
to setTimeout(fn, 0), it's much more efficient.
process.nextTick(function () {
console.log('nextTick callback');
});
process.umask([mask])
Sets or reads the process's file mode creation mask. Child processes inherit the
mask from the parent process. Returns the old mask if mask argument is given,
otherwise returns the current mask.
util
These functions are in the module 'util'. Use require('util') to access
them.
util.debug(string)
A synchronous output function. Will block the process and
output string immediately to stderr.
require('util').debug('message on stderr');
util.log(string)
Output with timestamp on stdout.
require('util').log('Timestmaped message.');
util.inspect(object, showHidden=false,
depth=2)
Return a string representation of object, which is useful for debugging.
If showHidden is true, then the object's non-enumerable properties will be
shown too.
If depth is provided, it tells inspect how many times to recurse while
formatting the object. This is useful for inspecting large complicated objects.
The default is to only recurse twice. To make it recurse indefinitely, pass
in null for depth.
Example of inspecting all properties of the util object:
util.pump(readableStream, writableStream,
[callback])
Experimental
util.inherits(constructor, superConstructor)
Inherit the prototype methods from one constructor into another. The prototype
of constructor will be set to a new object created from superConstructor.
As an additional convenience, superConstructor will be accessible through
the constructor.super_property.
function MyStream() {
events.EventEmitter.call(this);
}
util.inherits(MyStream, events.EventEmitter);
MyStream.prototype.write = function(data) {
this.emit("data", data);
}
stream.on("data", function(data) {
console.log('Received data: "' + data + '"');
})
stream.write("It works!"); // Received data: "It works!"
Events
Many objects in Node emit events: a net.Server emits an event each time a peer
connects to it, afs.readStream emits an event when the file is opened. All
objects which emit events are instances ofevents.EventEmitter. You can
access this module by doing: require("events");
Typically, event names are represented by a camel-cased string, however, there
aren't any strict restrictions on that, as any string will be accepted.
events.EventEmitter
To access the EventEmitter class, require('events').EventEmitter.
When an EventEmitter instance experiences an error, the typical action is to
emit an 'error' event. Error events are treated as a special case in node. If there
is no listener for it, then the default action is to print a stack trace and exit the
program.
All EventEmitters emit the event 'newListener' when new listeners are added.
emitter.addListener(event, listener)
emitter.on(event, listener)
Adds a listener to the end of the listeners array for the specified event.
emitter.once(event, listener)
Adds a one time listener for the event. The listener is invoked only the first time
the event is fired, after which it is removed.
emitter.removeListener(event, listener)
Remove a listener from the listener array for the specified event. Caution:
changes array indices in the listener array behind the listener.
emitter.removeAllListeners(event)
Removes all listeners from the listener array for the specified event.
emitter.setMaxListeners(n)
By default EventEmitters will print a warning if more than 10 listeners are added
to it. This is a useful default which helps finding memory leaks. Obviously not all
Emitters should be limited to 10. This function allows that to be increased. Set to
zero for unlimited.
emitter.listeners(event)
Returns an array of listeners for the specified event. This array can be
manipulated, e.g. to remove listeners.
Event: 'newListener'
Buffers
Pure Javascript is Unicode friendly but not nice to binary data. When dealing
with TCP streams or the file system, it's necessary to handle octet streams. Node
has several strategies for manipulating, creating, and consuming octet streams.
Raw data is stored in instances of the Buffer class. A Buffer is similar to an
array of integers but corresponds to a raw memory allocation outside the V8 heap.
A Buffer cannot be resized.
The Buffer object is global.
Converting between Buffers and JavaScript string objects requires an explicit
encoding method. Here are the different string encodings;
'ascii' - for 7 bit ASCII data only. This encoding method is very fast,
and will strip the high bit if set.
'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
only 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
the first 8 bits of each character. This encoding method is deprecated and
should be avoided in favor of Buffer objects where possible. This encoding
will be removed in future versions of Node.
new Buffer(size)
Allocates a new buffer of size octets.
new Buffer(array)
Allocates a new buffer using an array of octets.
buffer.write(string, offset=0,
encoding='utf8')
Writes string to the buffer at offset using the given encoding. Returns number
of octets written. If bufferdid not contain enough space to fit the entire string, it
will write a partial amount of the string. In the case of'utf8' encoding, the
method will not write partial characters.
Example: write a utf8 string into a buffer, then print it
buf = new Buffer(256);
len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(len + " bytes: " + buf.toString('utf8', 0, len));
// 12 bytes: 陆 + 录 = 戮
buffer.toString(encoding, start=0,
end=buffer.length)
Decodes and returns a string from buffer data encoded with encoding beginning
at start and ending at end.
See buffer.write() example, above.
buffer[index]
Get and set the octet at index. The values refer to individual bytes, so the legal
range is between 0x00 and0xFF hex or 0 and 255.
Example: copy an ASCII string into a buffer, one byte at a time:
str = "node.js";
buf = new Buffer(str.length);
console.log(buf);
// node.js
Buffer.isBuffer(obj)
Tests if obj is a Buffer.
Buffer.byteLength(string, encoding='utf8')
Gives the actual byte length of a string. This is not the same
as String.prototype.length since that returns the number of characters in a
string.
Example:
// 陆 + 录 = 戮: 9 characters, 12 bytes
buffer.length
The size of the buffer in bytes. Note that this is not necessarily the size of the
contents. length refers to the amount of memory allocated for the buffer object.
It does not change when the contents of the buffer are changed.
console.log(buf.length);
buf.write("some string", "ascii", 0);
console.log(buf.length);
// 1234
// 1234
buffer.copy(targetBuffer, targetStart=0,
sourceStart=0, sourceEnd=buffer.length)
Does a memcpy() between buffers.
Example: build two Buffers, then copy buf1 from byte 16 through byte 19
into buf2, starting at the 8th byte inbuf2.
// !!!!!!!!qrst!!!!!!!!!!!!!
buffer.slice(start, end=buffer.length)
Returns a new buffer which references the same memory as the old, but offset
and cropped by the start andend indexes.
Modifying the new buffer slice will modify memory in the original
buffer!
Example: build a Buffer with the ASCII alphabet, take a slice, then modify one
byte from the original Buffer.
// abc
// !bc
Streams
A stream is an abstract interface implemented by various objects in Node. For
example a request to an HTTP server is a stream, as is stdout. Streams are
readable, writable, or both. All streams are instances ofEventEmitter.
Readable Stream
A Readable Stream has the following methods, members, and events.
Event: 'data'
function (data) { }
The 'data' event emits either a Buffer (by default) or a string
if setEncoding() was used.
Event: 'end'
function () { }
Emitted when the stream has received an EOF (FIN in TCP terminology).
Indicates that no more 'data'events will happen. If the stream is also writable, it
may be possible to continue writing.
Event: 'error'
function (exception) { }
Emitted if there was an error receiving data.
Event: 'close'
function () { }
Emitted when the underlying file descriptor has been closed. Not all streams will
emit this. (For example, an incoming HTTP request will not emit 'close'.)
Event: 'fd'
function (fd) { }
Emitted when a file descriptor is received on the stream. Only UNIX streams
support this functionality; all others will simply never emit this event.
stream.readable
A boolean that is true by default, but turns false after an 'error' occurred,
the stream came to an 'end', or destroy() was called.
stream.setEncoding(encoding)
Makes the data event emit a string instead of a Buffer. encoding can
be 'utf8', 'ascii', or 'base64'.
stream.pause()
Pauses the incoming 'data' events.
stream.resume()
Resumes the incoming 'data' events after a pause().
stream.destroy()
Closes the underlying file descriptor. Stream will not emit any more events.
stream.destroySoon()
After the write queue is drained, close the file descriptor.
stream.pipe(destination, [options])
This is a Stream.prototype method available on all Streams.
Connects this read stream to destination WriteStream. Incoming data on this
stream gets written todestination. The destination and source streams are kept
in sync by pausing and resuming as necessary.
Emulating the Unix cat command:
process.stdin.resume();
process.stdin.pipe(process.stdout);
By default end() is called on the destination when the source stream emits end,
so that destination is no longer writable. Pass { end: false } as options to
keep the destination stream open.
This keeps process.stdout open so that "Goodbye" can be written at the end.
process.stdin.resume();
process.stdin.on("end", function() {
process.stdout.write("Goodbye\n");
});
NOTE: If the source stream does not support pause() and resume(), this
function adds simple definitions which simply
emit 'pause' and 'resume' events on the source stream.
Writable Stream
A Writable Stream has the following methods, members, and events.
Event: 'drain'
function () { }
Emitted after a write() method was called that returned false to indicate that
it is safe to write again.
Event: 'error'
function (exception) { }
Emitted on error with the exception exception.
Event: 'close'
function () { }
Emitted when the underlying file descriptor has been closed.
Event: 'pipe'
function (src) { }
Emitted when the stream is passed to a readable stream's pipe method.
stream.writable
A boolean that is true by default, but turns false after an 'error' occurred
or end() / destroy() was called.
stream.write(buffer)
Same as the above except with a raw buffer.
stream.end()
Terminates the stream with EOF or FIN.
stream.end(string, encoding)
Sends string with the given encoding and terminates the stream with EOF or
FIN. This is useful to reduce the number of packets sent.
stream.end(buffer)
Same as above but with a buffer.
stream.destroy()
Closes the underlying file descriptor. Stream will not emit any more events.
stream.destroySoon()
After the write queue is drained, close the file descriptor. destroySoon() can
still destroy straight away, as long as there is no data left in the queue for writes.
Crypto
Use require('crypto') to access this module.
The crypto module requires OpenSSL to be available on the underlying platform.
It offers a way of encapsulating secure credentials to be used as part of a secure
HTTPS net or http connection.
It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign
and verify methods.
crypto.createCredentials(details)
Creates a credentials object, with the optional details being a dictionary with keys:
If no 'ca' details are given, then node.js will use the default publicly trusted list of
CAs as given
inhttp://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata
.txt.
crypto.createHash(algorithm)
Creates and returns a hash object, a cryptographic hash with the given algorithm
which can be used to generate hash digests.
hash.update(data)
Updates the hash content with the given data. This can be called many times
with new data as it is streamed.
hash.digest(encoding='binary')
Calculates the digest of all of the passed data to be hashed. The encoding can
be 'hex', 'binary' or'base64'.
crypto.createHmac(algorithm, key)
Creates and returns a hmac object, a cryptographic hmac with the given
algorithm and key.
hmac.update(data)
Update the hmac content with the given data. This can be called many times with
new data as it is streamed.
hmac.digest(encoding='binary')
Calculates the digest of all of the passed data to the hmac. The encoding can
be 'hex', 'binary' or'base64'.
crypto.createCipher(algorithm, key)
Creates and returns a cipher object, with the given algorithm and key.
cipher.update(data, input_encoding='binary',
output_encoding='binary')
Updates the cipher with data, the encoding of which is given
in input_encoding and can be 'utf8','ascii' or 'binary'.
The output_encoding specifies the output format of the enciphered data, and
can be'binary', 'base64' or 'hex'.
Returns the enciphered contents, and can be called many times with new data as
it is streamed.
cipher.final(output_encoding='binary')
Returns any remaining enciphered contents, with output_encoding being one
of: 'binary', 'ascii' or'utf8'.
crypto.createDecipher(algorithm, key)
Creates and returns a decipher object, with the given algorithm and key. This is
the mirror of the cipher object above.
decipher.update(data,
input_encoding='binary',
output_encoding='binary')
Updates the decipher with data, which is encoded
in 'binary', 'base64' or 'hex'. The output_decodingspecifies in what
format to return the deciphered plaintext: 'binary', 'ascii' or 'utf8'.
decipher.final(output_encoding='binary')
Returns any remaining plaintext which is deciphered, with output_encoding'
being one of: 'binary','ascii' or 'utf8'`.
crypto.createSign(algorithm)
Creates and returns a signing object, with the given algorithm. On recent
OpenSSL releases, openssl list-public-key-algorithms will display the
available signing algorithms. Examples are 'RSA-SHA256'.
signer.update(data)
Updates the signer object with data. This can be called many times with new data
as it is streamed.
signer.sign(private_key,
output_format='binary')
Calculates the signature on all the updated data passed through the
signer. private_key is a string containing the PEM encoded private key for
signing.
Returns the signature in output_format which can
be 'binary', 'hex' or 'base64'.
crypto.createVerify(algorithm)
Creates and returns a verification object, with the given algorithm. This is the
mirror of the signing object above.
verifier.update(data)
Updates the verifier object with data. This can be called many times with new
data as it is streamed.
verifier.verify(cert, signature,
signature_format='binary')
Verifies the signed data by using the cert which is a string containing the PEM
encoded public key, andsignature, which is the previously calculates signature
for the data, in the signature_format which can
be'binary', 'hex' or 'base64'.
Returns true or false depending on the validity of the signature for the data and
public key.
TLS (SSL)
Use require('tls') to access this module.
The tls module uses OpenSSL to provide Transport Layer Security and/or
Secure Socket Layer: encrypted stream communication.
TLS/SSL is a public/private key infrastructure. Each client and each server must
have a private key. A private key is created like this
All severs and some clients need to have a certificate. Certificates are public keys
signed by a Certificate Authority or self-signed. The first step to getting a
certificate is to create a "Certificate Signing Request" (CSR) file. This is done with:
Alternatively you can send the CSR to a Certificate Authority for signing.
(TODO: docs on creating a CA, for now interested users should just look
at test/fixtures/keys/Makefile in the Node source code)
tls.Server
This class is a subclass of net.Server and has the same methods on it. Instead
of accepting just raw TCP connections, this accepts encrypted connections using
TLS or SSL.
Here is a simple example echo server:
var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
};
tls.createServer(options, secureConnectionListener)
This is a constructor for the tls.Server class. The options object has these
possibilities:
key: A string or Buffer containing the private key of the server in PEM
format. (Required)
cert: A string or Buffer containing the certificate key of the server in
PEM format. (Required)
ca: An array of strings or Buffers of trusted certificates. If this is omitted
several well known "root" CAs will be used, like VeriSign. These are used to
authorize connections.
requestCert: If true the server will request a certificate from clients
that connect and attempt to verify that certificate. Default: false.
rejectUnauthorized: If true the server will reject any connection
which is not authorized with the list of supplied CAs. This option only has an
effect if requestCert is true. Default: false.
Event: 'secureConnection'
function (cleartextStream) {}
This event is emitted after a new connection has been successfully handshaked.
The argument is a duplex instance of stream.Stream. It has all the common
stream methods and events.
cleartextStream.authorized is a boolean value which indicates if the client
has verified by one of the supplied certificate authorities for the server.
If cleartextStream.authorized is false,
thencleartextStream.authorizationError is set to describe how
authorization failed. Implied but worth mentioning: depending on the settings of
the TLS server, you unauthorized connections may be accepted.
server.close()
Stops the server from accepting new connections. This function is asynchronous,
the server is finally closed when the server emits a 'close' event.
server.maxConnections
Set this property to reject connections when the server's connection count gets
high.
server.connections
File System
File I/O is provided by simple wrappers around standard POSIX functions. To
use this module dorequire('fs'). All the methods have asynchronous and
synchronous forms.
The asynchronous form always take a completion callback as its last argument.
The arguments passed to the completion callback depend on the method, but the
first argument is always reserved for an exception. If the operation was completed
successfully, then the first argument will be null or undefined.
Here is an example of the asynchronous version:
var fs = require('fs');
var fs = require('fs');
fs.unlinkSync('/tmp/hello')
console.log('successfully deleted /tmp/hello');
fs.renameSync(path1, path2)
Synchronous rename(2).
fs.truncateSync(fd, len)
Synchronous ftruncate(2).
fs.chmodSync(path, mode)
Synchronous chmod(2).
fs.stat(path, [callback])
Asynchronous stat(2). The callback gets two arguments (err,
stats) where stats is a fs.Stats object. It looks like this:
{ dev: 2049,
ino: 305352,
mode: 16877,
nlink: 12,
uid: 1000,
gid: 1000,
rdev: 0,
size: 4096,
blksize: 4096,
blocks: 8,
atime: '2009-06-29T11:11:55Z',
mtime: '2009-06-29T11:11:40Z',
ctime: '2009-06-29T11:11:40Z' }
fs.lstat(path, [callback])
Asynchronous lstat(2). The callback gets two arguments (err,
stats) where stats is a fs.Stats object. lstat() is identical to stat(), except
that if path is a symbolic link, then the link itself is stat-ed, not the file that it
refers to.
fs.fstat(fd, [callback])
Asynchronous fstat(2). The callback gets two arguments (err,
stats) where stats is a fs.Stats object.
fs.statSync(path)
Synchronous stat(2). Returns an instance of fs.Stats.
fs.lstatSync(path)
Synchronous lstat(2). Returns an instance of fs.Stats.
fs.fstatSync(fd)
Synchronous fstat(2). Returns an instance of fs.Stats.
fs.link(srcpath, dstpath, [callback])
Asynchronous link(2). No arguments other than a possible exception are given to
the completion callback.
fs.linkSync(srcpath, dstpath)
Synchronous link(2).
fs.symlinkSync(linkdata, path)
Synchronous symlink(2).
fs.readlink(path, [callback])
Asynchronous readlink(2). The callback gets two arguments (err,
resolvedPath).
fs.readlinkSync(path)
Synchronous readlink(2). Returns the resolved path.
fs.realpath(path, [callback])
Asynchronous realpath(2). The callback gets two arguments (err,
resolvedPath).
fs.realpathSync(path)
Synchronous realpath(2). Returns the resolved path.
fs.unlink(path, [callback])
Asynchronous unlink(2). No arguments other than a possible exception are given
to the completion callback.
fs.unlinkSync(path)
Synchronous unlink(2).
fs.rmdir(path, [callback])
Asynchronous rmdir(2). No arguments other than a possible exception are given
to the completion callback.
fs.rmdirSync(path)
Synchronous rmdir(2).
fs.mkdirSync(path, mode)
Synchronous mkdir(2).
fs.readdir(path, [callback])
Asynchronous readdir(3). Reads the contents of a directory. The callback gets two
arguments (err, files)where files is an array of the names of the files in the
directory excluding '.' and '..'.
fs.readdirSync(path)
Synchronous readdir(3). Returns an array of filenames excluding '.' and '..'.
fs.close(fd, [callback])
Asynchronous close(2). No arguments other than a possible exception are given
to the completion callback.
fs.closeSync(fd)
Synchronous close(2).
The callback is passed two arguments (err, data), where data is the contents
of the file.
If no encoding is specified, then the raw buffer is returned.
fs.readFileSync(filename, [encoding])
Synchronous version of fs.readFile. Returns the contents of the filename.
If encoding is specified then this function returns a string. Otherwise it returns a
buffer.
fs.writeFileSync(filename, data,
encoding='utf8')
The synchronous version of fs.writeFile.
fs.unwatchFile(filename)
Stop watching for changes on filename.
fs.Stats
Objects returned from fs.stat() and fs.lstat() are of this type.
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
fs.ReadStream
ReadStream is a Readable Stream.
fs.createReadStream(path, [options])
Returns a new ReadStream object (See Readable Stream).
options is an object with the following defaults:
{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
bufferSize: 64 * 1024
}
options can include start and end values to read a range of bytes from the file
instead of the entire file. Bothstart and end are inclusive and start at 0. When
used, both the limits must be specified always.
An example to read the last 10 bytes of a file which is 100 bytes long:
fs.WriteStream
WriteStream is a Writable Stream.
Event: 'open'
function (fd) { }
fd is the file descriptor used by the WriteStream.
fs.createWriteStream(path, [options])
Returns a new WriteStream object (See Writable Stream).
options is an object with the following defaults:
{ flags: 'w',
encoding: null,
mode: 0666 }
Path
This module contains utilities for dealing with file paths.
Use require('path') to use it. It provides the following methods:
path.normalize(p)
Normalize a string path, taking care of '..' and '.' parts.
When multiple slashes are found, they're replaces by a single one; when the path
contains a trailing slash, it is preserved. On windows backslashes are used.
Example:
path.normalize('/foo/bar//baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'
Example:
node> require('path').join(
... '/foo', 'bar', 'baz/asdf', 'quux', '..')
'/foo/bar/baz/asdf'
cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd
The difference is that the different paths don't need to exist and may also be files.
Examples:
path.resolve('/foo/bar', './baz')
// returns
'/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
// returns
'/tmp/file'
path.dirname(p)
Return the directory name of a path. Similar to the Unix dirname command.
Example:
path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'
path.basename(p, [ext])
Return the last portion of a path. Similar to the Unix basename command.
Example:
path.basename('/foo/bar/baz/asdf/quux.html')
// returns
'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
'quux'
path.extname(p)
Return the extension of the path. Everything after the last '.' in the last portion of
the path. If there is no '.' in the last portion of the path or the only '.' is the first
character, then it returns an empty string. Examples:
path.extname('index.html')
// returns
'.html'
path.extname('index')
// returns
''
path.exists(p, [callback])
Test whether or not the given path exists. Then, call the callback argument with
either true or false. Example:
path.existsSync(p)
Synchronous version of path.exists.
net
The net module provides you with an asynchronous network wrapper. It contains
methods for creating both servers and clients (called streams). You can include
this module with require("net");
net.createServer([options],
[connectionListener])
Creates a new TCP server. The connectionListener argument is automatically
set as a listener for the'connection' event.
options is an object with the following defaults:
{ allowHalfOpen: false
}
If allowHalfOpen is true, then the socket won't automatically send FIN packet
when the other end of the socket sends a FIN packet. The socket becomes
non-readable, but still writable. You should call the end() method explicitly.
See 'end' event for more information.
net.createConnection(arguments...)
Construct a new socket object and opens a socket to the given location. When the
socket is established the'connect' event will be emitted.
The arguments for this method change the type of connection:
net.createConnection(port, [host])
Creates a TCP connection to port on host. If host is
omitted, localhost will be assumed.
net.createConnection(path)
Creates unix socket connection to path
net.Server
This class is used to create a TCP or UNIX server.
Here is an example of a echo server which listens for connections on port 8124:
To listen on the socket /tmp/echo.sock the last line would just be changed to
server.listen('/tmp/echo.sock');
Use nc to connect to a UNIX domain socket server:
nc -U /tmp/echo.sock
Begin accepting connections on the specified port and host. If the host is
omitted, the server will accept connections directed to any IPv4 address
(INADDR_ANY).
This function is asynchronous. The last parameter callback will be called when
the server has been bound.
One issue some users run into is getting EADDRINUSE errors. Meaning another
server is already running on the requested port. One way of handling this would
be to wait a second and the try again. This can be done with
server.listen(path, [callback])
Start a UNIX socket server listening for connections on the given path.
This function is asynchronous. The last parameter callback will be called when
the server has been bound.
server.listenFD(fd)
Start a server listening for connections on the given file descriptor.
This file descriptor must have already had the bind(2) and listen(2) system
calls invoked on it.
server.close()
Stops the server from accepting new connections. This function is asynchronous,
the server is finally closed when the server emits a 'close' event.
server.address()
Returns the bound address of the server as seen by the operating system. Useful
to find which port was assigned when giving getting an OS-assigned address
Example:
server.maxConnections
Set this property to reject connections when the server's connection count gets
high.
server.connections
The number of concurrent connections on the server.
Event: 'connection'
function (socket) {}
Emitted when a new connection is made. socket is an instance of net.Socket.
Event: 'close'
function () {}
Emitted when the server closes.
net.Socket
This object is an abstraction of of a TCP or UNIX socket. net.Socket instances
implement a duplex Stream interface. They can be created by the user and used as
a client (with connect()) or they can be created by Node and passed to the user
through the 'connection' event of a server.
net.Socket instances are EventEmitters with the following events:
new net.Socket([options])
{ fd: null
type: null
allowHalfOpen: false
}
fd allows you to specify the existing file descriptor of socket. type specified
underlying protocol. It can be'tcp4', 'tcp6', or 'unix'.
About allowHalfOpen, refer to createServer() and 'end' event.
socket.connect(path, [callback])
Opens the connection for a given socket. If port and host are given, then the
socket will be opened as a TCP socket, if host is omitted, localhost will be
assumed. If a path is given, the socket will be opened as a unix socket to that
path.
Normally this method is not needed, as net.createConnection opens the
socket. Use this only if you are implementing a custom Socket or if a Socket is
closed and you want to reuse it to connect to another server.
This function is asynchronous. When the 'connect' event is emitted the socket
is established. If there is a problem connecting, the 'connect' event will not be
emitted, the 'error' event will be emitted with the exception.
The callback parameter will be added as an listener for the 'connect' event.
socket.bufferSize
socket.setEncoding(encoding=null)
Sets the encoding (either 'ascii', 'utf8', or 'base64') for data that is
received.
socket.setSecure()
This function has been removed in v0.3. It used to upgrade the connection to
SSL/TLS. See the TLS for the new API.
Sends data on the socket. The second parameter specifies the encoding in the case
of a string--it defaults to UTF8 encoding.
Returns true if the entire data was flushed successfully to the kernel buffer.
Returns false if all or part of the data was queued in user memory. 'drain' will
be emitted when the buffer is again free.
The optional callback parameter will be executed when the data is finally
written out - this may not be immediately.
[callback])
For UNIX sockets, it is possible to send a file descriptor through the socket.
Simply add the fileDescriptorargument and listen for the 'fd' event on the
other end.
socket.end([data], [encoding])
Half-closes the socket. I.E., it sends a FIN packet. It is possible the server will still
send some data.
socket.destroy()
Ensures that no more I/O activity happens on this socket. Only necessary in case
of errors (parse error or so).
socket.pause()
Pauses the reading of data. That is, 'data' events will not be emitted. Useful to
throttle back an upload.
socket.resume()
socket.setTimeout(timeout, [callback])
Sets the socket to timeout after timeout milliseconds of inactivity on the socket.
By default net.Socket do not have a timeout.
When an idle timeout is triggered the socket will receive a 'timeout' event but
the connection will not be severed. The user must
manually end() or destroy() the socket.
If timeout is 0, then the existing idle timeout is disabled.
The optional callback parameter will be added as a one time listener for
the 'timeout' event.
socket.setNoDelay(noDelay=true)
Disables the Nagle algorithm. By default TCP connections use the Nagle
algorithm, they buffer data before sending it off. Setting noDelay will
immediately fire off data each time socket.write() is called.
socket.setKeepAlive(enable=false, [initialDelay])
Enable/disable keep-alive functionality, and optionally set the initial delay before
the first keepalive probe is sent on an idle socket. Set initialDelay (in
milliseconds) to set the delay between the last data packet received and the first
keepalive probe. Setting 0 for initialDelay will leave the value unchanged from the
default (or previous) setting.
socket.remoteAddress
Event: 'connect'
function () { }
Emitted when a socket connection successfully is established. See connect().
Event: 'data'
function (data) { }
Emitted when data is received. The argument data will be a Buffer or String.
Encoding of data is set bysocket.setEncoding(). (See the section
on Readable Socket for more information.)
Event: 'end'
function () { }
Emitted when the other end of the socket sends a FIN packet.
By default (allowHalfOpen == false) the socket will destroy its file descriptor
once it has written out its pending write queue. However, by
setting allowHalfOpen == true the socket will not automatically end() its side
allowing the user to write arbitrary amounts of data, with the caveat that the user
is required to end() their side now.
Event: 'timeout'
function () { }
Emitted if the socket times out from inactivity. This is only to notify that the
socket has been idle. The user must manually close the connection.
function () { }
Emitted when the write buffer becomes empty. Can be used to throttle uploads.
Event: 'error'
function (exception) { }
Emitted when an error occurs. The 'close' event will be called directly
following this event.
Event: 'close'
function (had_error) { }
Emitted once the socket is fully closed. The argument had_error is a boolean
which says if the socket was closed due to a transmission error.
net.isIP
net.isIP(input)
net.isIPv4(input)
net.isIPv6(input)
addresses.forEach(function (a) {
dns.reverse(a, function (err, domains) {
if (err) {
console.log('reverse for ' + a + ' failed: ' +
err.message);
} else {
console.log('reverse for ' + a + ': ' +
JSON.stringify(domains));
}
});
});
});
dns.resolve4(domain, callback)
The same as dns.resolve(), but only for IPv4 queries
(A records). addresses is an array of IPv4 addresses (e.g. ['74.125.79.104',
'74.125.79.105', '74.125.79.106']).
dns.resolve6(domain, callback)
The same as dns.resolve4() except for IPv6 queries (an AAAA query).
dns.resolveMx(domain, callback)
The same as dns.resolve(), but only for mail exchange queries (MX records).
addresses is an array of MX records, each with a priority and an exchange
attribute (e.g. [{'priority': 10, 'exchange': 'mx.example.com'},...]).
dns.resolveTxt(domain, callback)
The same as dns.resolve(), but only for text queries
(TXT records). addresses is an array of the text records available
for domain (e.g., ['v=spf1 ip4:0.0.0.0 ~all']).
dns.resolveSrv(domain, callback)
The same as dns.resolve(), but only for service records
(SRV records). addresses is an array of the SRV records available for domain.
Properties of SRV records are priority, weight, port, and name
(e.g.,[{'priority': 10, {'weight': 5, 'port': 21223, 'name':
'service.example.com'}, ...]).
dns.reverse(ip, callback)
Reverse resolves an ip address to an array of domain names.
Event: 'message'
function (msg, rinfo) { }
Emitted when a new datagram is available on a socket. msg is
a Buffer and rinfo is an object with the sender's address information and the
number of bytes in the datagram.
Event: 'listening'
function () { }
Emitted when a socket starts listening for datagrams. This happens as soon as
UDP sockets are created. Unix domain sockets do not start listening until
calling bind() on them.
Event: 'close'
function () { }
Emitted when a socket is closed with close(). No new message events will be
emitted on this socket.
dgram.createSocket(type, [callback])
Creates a datagram socket of the specified types. Valid types are: udp4, udp6,
and unix_dgram.
Takes an optional callback which is added as a listener for message events.
dgram.bind(path)
For Unix domain datagram sockets, start listening for incoming datagrams on a
socket specified by path. Note that clients may send() without bind(), but no
datagrams will be received without a bind().
Example of a Unix domain datagram server that echoes back all messages it
receives:
server.on("listening", function () {
console.log("server listening " + server.address().address);
})
server.bind(serverPath);
client.on("listening", function () {
console.log("client listening " + client.address().address);
client.send(message, 0, message.length, serverPath);
});
client.bind(clientPath);
dgram.bind(port, [address])
For UDP sockets, listen for datagrams on a named port and optional address.
If address is not specified, the OS will try to listen on all addresses.
Example of a UDP server listening on port 41234:
server.on("listening", function () {
var address = server.address();
console.log("server listening " +
address.address + ":" + address.port);
});
server.bind(41234);
// server listening 0.0.0.0:41234
dgram.close()
Close the underlying socket and stop listening for data on it. UDP sockets
automatically listen for messages, even if they did not call bind().
dgram.address()
Returns an object containing the address information for a socket. For UDP
sockets, this object will containaddress and port. For Unix domain sockets, it
will contain only address.
dgram.setBroadcast(flag)
Sets or clears the SO_BROADCAST socket option. When this option is set, UDP
packets may be sent to a local interface's broadcast address.
dgram.setTTL(ttl)
Sets the IP_TTL socket option. TTL stands for "Time to Live," but in this context
it specifies the number of IP hops that a packet is allowed to go through. Each
router or gateway that forwards a packet decrements the TTL. If the TTL is
decremented to 0 by a router, it will not be forwarded. Changing TTL values is
typically done for network probes or when multicasting.
The argument to setTTL() is a number of hops between 1 and 255. The default
on most systems is 64.
dgram.setMulticastTTL(ttl)
Sets the IP_MULTICAST_TTL socket option. TTL stands for "Time to Live," but in
this context it specifies the number of IP hops that a packet is allowed to go
through, specifically for multicast traffic. Each router or gateway that forwards a
packet decrements the TTL. If the TTL is decremented to 0 by a router, it will not
be forwarded.
The argument to setMulticastTTL() is a number of hops between 0 and 255.
The default on most systems is 64.
dgram.setMulticastLoopback(flag)
Sets or clears the IP_MULTICAST_LOOP socket option. When this option is set,
multicast packets will also be received on the local interface.
dgram.addMembership(multicastAddress,
[multicastInterface])
Tells the kernel to join a multicast group with IP_ADD_MEMBERSHIP socket
option.
If multicastAddress is not specified, the OS will try to add membership to all
valid interfaces.
dgram.dropMembership(multicastAddress,
[multicastInterface])
Opposite of addMembership - tells the kernel to leave a multicast group
with IP_DROP_MEMBERSHIP socket option. This is automatically called by the
kernel when the socket is closed or process terminates, so most apps will never
need to call this.
If multicastAddress is not specified, the OS will try to drop membership to all
valid interfaces.
HTTP
To use the HTTP server and client one must require('http').
The HTTP interfaces in Node are designed to support many features of the
protocol which have been traditionally difficult to use. In particular, large,
possibly chunk-encoded, messages. The interface is careful to never buffer entire
requests or responses--the user is able to stream data.
{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive',
'accept': '*/*' }
In order to support the full spectrum of possible HTTP applications, Node's HTTP
API is very low-level. It deals with stream handling and message parsing only. It
parses a message into headers and body but it does not parse the actual headers
or the body.
http.Server
This is an EventEmitter with the following events:
Event: 'request'
function (request, response) { }
request is an instance of http.ServerRequest and response is an instance
of http.ServerResponse
Event: 'connection'
function (stream) { }
When a new TCP stream is established. stream is an object of type net.Stream.
Usually users will not want to access this event. The stream can also be accessed
at request.connection.
Event: 'close'
function (errno) { }
Emitted when the server closes.
Event: 'request'
function (request, response) {}
Emitted each time there is request. Note that there may be multiple requests per
connection (in the case of keep-alive connections).
Event: 'checkContinue'
function (request, response) {}
Emitted each time a request with an http Expect: 100-continue is received. If this
event isn't listened for, the server will automatically respond with a 100 Continue
as appropriate.
Event: 'upgrade'
function (request, socket, head)
Emitted each time a client requests a http upgrade. If this event isn't listened for,
then clients requesting an upgrade will have their connections closed.
request 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 event listener,
meaning you will need to bind to it in order to handle data sent to the server on
that socket.
Event: 'clientError'
function (exception) {}
If a client connection emits an 'error' event - it will forwarded here.
http.createServer(requestListener)
Returns a new web server object.
This function is asynchronous. The last parameter callback will be called when
the server has been bound to the port.
server.listen(path, [callback])
Start a UNIX socket server listening for connections on the given path.
This function is asynchronous. The last parameter callback will be called when
the server has been bound.
server.close()
Stops the server from accepting new connections.
http.ServerRequest
This object is created internally by a HTTP server -- not by the user -- and passed
as the first argument to a'request' listener.
This is an EventEmitter with the following events:
Event: 'data'
function (chunk) { }
Emitted when a piece of the message body is received.
Example: A chunk of the body is given as the single argument. The
transfer-encoding has been decoded. The body chunk is a string. The body
encoding is set with request.setBodyEncoding().
Event: 'end'
function () { }
Emitted exactly once for each message. No arguments. After emitted no other
events will be emitted on the request.
request.method
The request method as a string. Read only. Example: 'GET', 'DELETE'.
request.url
Request URL string. This contains only the URL that is present in the actual
HTTP request. If the request is:
'/status?name=ryan'
If you would like to parse the URL into its parts, you can
use require('url').parse(request.url). Example:
node> require('url').parse('/status?name=ryan')
{ href: '/status?name=ryan',
search: '?name=ryan',
query: 'name=ryan',
pathname: '/status' }
If you would like to extract the params from the query string, you can use
therequire('querystring').parse function, or pass true as the second
argument to require('url').parse. Example:
request.headers
Read only.
request.trailers
Read only; HTTP trailers (if present). Only populated after the 'end' event.
request.httpVersion
The HTTP protocol version as a string. Read only. Examples: '1.1', '1.0'.
Also request.httpVersionMajoris the first integer
and request.httpVersionMinor is the second.
request.setEncoding(encoding=null)
Set the encoding for the request body. Either 'utf8' or 'binary'. Defaults
to null, which means that the'data' event will emit a Buffer object..
request.pause()
Pauses request from emitting events. Useful to throttle back an upload.
request.resume()
Resumes a paused request.
request.connection
The net.Stream object associated with the connection.
With HTTPS support, use request.connection.verifyPeer() and
request.connection.getPeerCertificate() to obtain the client's authentication
details.
http.ServerResponse
This object is created internally by a HTTP server--not by the user. It is passed as
the second parameter to the'request' event. It is a Writable Stream.
response.writeContinue()
Sends a HTTP/1.1 100 Continue message to the client, indicating that the request
body should be sent. See the thecheckContinue event on Server.
response.writeHead(statusCode,
[reasonPhrase], [headers])
Sends a response header to the request. The status code is a 3-digit HTTP status
code, like 404. The last argument, headers, are the response headers. Optionally
one can give a human-readable reasonPhrase as the second argument.
Example:
This method must only be called once on a message and it must be called
before response.end() is called.
If you call response.write() or response.end() before calling this, the
implicit/mutable headers will be calculated and call this function for you.
response.statusCode
When using implicit headers (not calling response.writeHead() explicitly),
this property controls the status code that will be send to the client when the
headers get flushed.
Example:
response.statusCode = 404;
response.setHeader(name, value)
Sets a single header value for implicit headers. If this header already exists in the
to-be-sent headers, it's value will be replaced. Use an array of strings here if you
need to send multiple headers with the same name.
Example:
response.setHeader("Content-Type", "text/html");
or
response.setHeader("Set-Cookie", ["type=ninja",
"language=javascript"]);
response.getHeader(name)
Reads out a header that's already been queued but not sent to the client. Note that
the name is case insensitive. This can only be called before headers get implicitly
flushed.
Example:
var contentType = response.getHeader('content-type');
response.removeHeader(name)
Removes a header that's queued for implicit sending.
Example:
response.removeHeader("Content-Encoding");
response.write(chunk, encoding='utf8')
If this method is called and response.writeHead() has not been called, it will
switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may be called multiple
times to provide successive parts of the body.
The first time response.write() is called, it will send the buffered header
information and the first body to the client. The second
time response.write() is called, Node assumes you're going to be streaming
data, and sends that separately. That is, the response is buffered up to the first
chunk of body.
response.addTrailers(headers)
This method adds HTTP trailing headers (a header but at the end of the message)
to the response.
Trailers will only be emitted if chunked encoding is used for the response; if it is
not (e.g., if the request was HTTP/1.0), they will be silently discarded.
Note that HTTP requires the Trailer header to be sent if you intend to emit
trailers, with a list of the header fields in its value. E.g.,
response.end([data], [encoding])
This method signals to the server that all of the response headers and body has
been sent; that server should consider this message complete. The
method, response.end(), MUST be called on each response.
If data is specified, it is equivalent to calling response.write(data,
encoding) followed byresponse.end().
http.request(options, callback)
Node maintains several connections per server to make HTTP requests. This
function allows one to transparently issue requests.
Options:
host: A domain name or IP address of the server to issue the request to.
port: Port of remote server.
method: A string specifying the HTTP request method. Possible
values: 'GET' (default), 'POST', 'PUT', and'DELETE'.
path: Request path. Should include query string and fragments if any.
E.G. '/index.html?page=12'
headers: An object containing request headers.
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
Note that in the example req.end() was called. With http.request() one
must always call req.end() to signify that you're done with the request - even if
there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution, TCP
level errors, or actual HTTP parse errors) an 'error' event is emitted on the
returned request object.
There are a few special headers that should be noted.
http.get(options, callback)
Since most requests are GET requests without bodies, Node provides this
convenience method. The only difference between this method
and http.request() is that it sets the method to GET and
calls req.end()automatically.
Example:
var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
http.Agent
http.getAgent(host, port)
http.request() uses a special Agent for managing multiple connections to an
HTTP server. Normally Agentinstances should not be exposed to user code,
however in certain situations it's useful to check the status of the agent.
The http.getAgent() function allows you to access the agents.
Event: 'upgrade'
function (request, socket, head)
Emitted each time a server responds to a request with an upgrade. If this event
isn't being listened for, clients receiving an upgrade header will have their
connections closed.
See the description of the upgrade event for http.Server for further details.
Event: 'continue'
function ()
Emitted when the server sends a '100 Continue' HTTP response, usually because
the request contained 'Expect: 100-continue'. This is an instruction that the client
should send the request body.
agent.maxSockets
By default set to 5. Determines how many concurrent sockets the agent can have
open.
agent.sockets
An array of sockets currently in use by the Agent. Do not modify.
agent.queue
A queue of requests waiting to be sent to sockets.
http.ClientRequest
This object is created internally and returned from http.request(). It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name,
value),getHeader(name), removeHeader(name) API. The actual header will
be sent along with the first data chunk or when closing the connection.
To get the response, add a listener for 'response' to the request
object. 'response' will be emitted from the request object when the response
headers have been received. The 'response' event is executed with one
argument which is an instance of http.ClientResponse.
During the 'response' event, one can add listeners to the response object;
particularly to listen for the 'data'event. Note that the 'response' event is
called before any part of the response body is received, so there is no need to
worry about racing to catch the first part of the body. As long as a listener
for 'data' is added during the 'response' event, the entire body will be
caught.
// Good
request.on('response', function (response) {
response.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
Event 'response'
function (response) { }
Emitted when a response is received to this request. This event is emitted only
once. The response argument will be an instance of http.ClientResponse.
request.write(chunk, encoding='utf8')
Sends a chunk of the body. By calling this method many times, the user can
stream a request body to a server--in that case it is suggested to use
the ['Transfer-Encoding', 'chunked'] header line when creating the
request.
The chunk argument should be an array of integers or a string.
The encoding argument is optional and only applies when chunk is a string.
request.end([data], [encoding])
Finishes sending the request. If any parts of the body are unsent, it will flush
them to the stream. If the request is chunked, this will send the
terminating '0\r\n\r\n'.
If data is specified, it is equivalent to calling request.write(data,
encoding) followed by request.end().
request.abort()
Aborts a request. (New since v0.3.8.)
http.ClientResponse
This object is created when making a request with http.request(). It is passed
to the 'response' event of the request object.
The response implements the Readable Stream interface.
Event: 'data'
function (chunk) {}
Emitted when a piece of the message body is received.
Event: 'end'
function () {}
Emitted exactly once for each message. No arguments. After emitted no other
events will be emitted on the response.
response.statusCode
The 3-digit HTTP response status code. E.G. 404.
response.httpVersion
The HTTP version of the connected-to server. Probably either '1.1' or '1.0'.
Alsoresponse.httpVersionMajor is the first integer
and response.httpVersionMinor is the second.
response.headers
The response headers object.
response.trailers
The response trailers object. Only populated after the 'end' event.
response.setEncoding(encoding=null)
Set the encoding for the response body. Either 'utf8', 'ascii', or 'base64'.
Defaults to null, which means that the 'data' event will emit a Buffer object..
response.pause()
Pauses response from emitting events. Useful to throttle back a download.
response.resume()
Resumes a paused response.
HTTPS
HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a
separate module.
https.Server
https.createServer
Example:
// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.request(options, callback)
Makes a request to a secure web server. Similar options to http.request().
Example:
var options = {
host: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});
https.get(options, callback)
Like http.get() but for HTTPS.
Example:
res.on('data', function(d) {
process.stdout.write(d);
});
}).on('error', function(e) {
console.error(e);
});
URL
This module has utilities for URL resolution and parsing.
Call require('url') to use it.
Parsed URL objects have some or all of the following fields, depending on
whether or not they exist in the URL string. Any parts that are not in the URL
string will not be in the parsed object. Examples are shown for the URL
'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
href: The full URL that was originally parsed.
Example: 'http://user:pass@host.com:8080/p/a/t/h?query=strin
g#hash'
protocol: The request protocol.
Example: 'http:'
host: The full host portion of the URL, including port and authentication
information.
Example: 'user:pass@host.com:8080'
auth: The authentication information portion of a URL.
Example: 'user:pass'
hostname: Just the 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
before the query, including the initial slash if present.
Example: '/p/a/t/h'
search: The 'query string' portion of the URL, including the leading
question mark.
Example: '?query=string'
query: Either the 'params' portion of the query string, or a
querystring-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:
url.parse(urlStr, parseQueryString=false)
Take a URL string, and return an object. Pass true as the second argument to
also parse the query string using the querystring module.
url.format(urlObj)
Take a parsed URL object, and return a formatted URL string.
url.resolve(from, to)
Take a base URL, and a href URL, and resolve them as a browser would for an
anchor tag.
Query String
This module provides utilities for dealing with query strings. It provides the
following methods:
Example:
querystring.stringify({foo: 'bar'})
// returns
'foo=bar'
Example:
querystring.parse('a=b&b=c')
// returns
{ a: 'b', b: 'c' }
querystring.escape
The escape function used by querystring.stringify, provided so that it could
be overridden if necessary.
querystring.unescape
The unescape function used by querystring.parse, provided so that it could
be overridden if necessary.
REPL
A Read-Eval-Print-Loop (REPL) is available both as a standalone program and
easily includable in other programs. REPL provides a way to interactively run
JavaScript and see the results. It can be used for debugging, testing, or just trying
things out.
By executing node without any arguments from the command-line you will be
dropped into the REPL. It has simplistic emacs line-editing.
mjr:~$ node
Type '.help' for options.
> a = [ 1, 2, 3];
[ 1, 2, 3 ]
> a.forEach(function (v) {
... console.log(v);
... });
1
2
3
For advanced line-editors, start node with the environmental
variable NODE_NO_READLINE=1. This will start the REPL in canonical terminal
settings which will allow you to use with rlwrap.
For example, you could add this to your bashrc file:
Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
connections = 0;
net.createServer(function (socket) {
connections += 1;
repl.start("node via Unix socket> ", socket);
}).listen("/tmp/node-repl-sock");
net.createServer(function (socket) {
connections += 1;
repl.start("node via TCP socket> ", socket);
}).listen(5001);
Running this program from the command line will start a REPL on stdin. Other
REPL clients may connect through the Unix socket or TCP socket. telnet is
useful for connecting to TCP sockets, and socat can be used to connect to both
Unix and TCP sockets.
By starting a REPL from a Unix socket-based server instead of stdin, you can
connect to a long-running node process without restarting it.
REPL Features
Inside the REPL, Control+D will exit. Multi-line expressions can be input.
The special variable _ (underscore) contains the result of the last expression.
The REPL provides access to any variables in the global scope. You can expose a
variable to the REPL explicitly by assigning it to the context object associated
with each REPLServer. For example:
// repl_test.js
var repl = require("repl"),
msg = "message";
repl.start().context.m = msg;
Child Processes
Node provides a tri-directional popen(3) facility through
the ChildProcess class.
It is possible to stream data through the child's stdin, stdout, and stderr in a
fully non-blocking way.
To create a child process use require('child_process').spawn().
Child processes always have three streams associated with
them. child.stdin, child.stdout, andchild.stderr.
ChildProcess is an EventEmitter.
Event: 'exit'
function (code, signal) {}
This event is emitted after the child process ends. If the process terminated
normally, code is the final exit code of the process, otherwise null. If the process
terminated due to receipt of a signal, signal is the string name of the signal,
otherwise null.
See waitpid(2).
child.stdin
A Writable Stream that represents the child process's stdin. Closing this
stream via end() often causes the child process to terminate.
child.stdout
A Readable Stream that represents the child process's stdout.
child.stderr
A Readable Stream that represents the child process's stderr.
child.pid
The PID of the child process.
Example:
child_process.spawn(command, args=[],
[options])
Launches a new process with the given command, with command line arguments
in args. If omitted, argsdefaults to an empty Array.
The third argument is used to specify additional options, which defaults to:
{ cwd: undefined,
env: process.env,
customFds: [-1, -1, -1],
setsid: false
}
cwd allows you to specify the working directory from which the process is
spawned. Use env to specify environment variables that will be visible to the new
process. With customFds it is possible to hook up the new process' [stdin, stout,
stderr] to existing streams; -1 means that a new stream should be
created. setsid, if set true, will cause the subprocess to be run in a new session.
Example of running ls -lh /usr, capturing stdout, stderr, and the exit code:
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});
child_process.exec(command, [options],
callback)
High-level way to execute a command as a child process, buffer the output, and
return it all in a callback.
{ encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null }
If timeout is greater than 0, then it will kill the child process if it runs longer
than timeout milliseconds. The child process is killed
with killSignal (default: 'SIGTERM'). maxBuffer specifies the largest amount
of data allowed on stdout or stderr - if this value is exceeded then the child
process is killed.
child.kill(signal='SIGTERM')
Send a signal to the child process. If no argument is given, the process will be
sent 'SIGTERM'. See signal(7)for a list of available signals.
Note that while the function is called kill, the signal delivered to the child
process may not actually kill it.kill really just sends a signal to a process.
See kill(2)
Assert
This module is used for writing unit tests for your applications, you can access it
with require('assert').
assert.ok(value, [message])
Tests if value is a true value, it is equivalent to assert.equal(true, value,
message);
assert.deepEqual(actual, expected,
[message])
Tests for deep equality.
assert.notDeepEqual(actual, expected,
[message])
Tests for any deep inequality.
assert.strictEqual(actual, expected,
[message])
Tests strict equality, as determined by the strict equality operator ( === )
assert.notStrictEqual(actual, expected,
[message])
Tests strict non-equality, as determined by the strict not equal operator ( !== )
assert.throws(
function() {
throw new Error("Wrong value");
},
Error
);
assert.throws(
function() {
throw new Error("Wrong value");
},
/value/
);
assert.throws(
function() {
throw new Error("Wrong value");
},
function(err) {
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
},
"unexpected error"
);
assert.doesNotThrow(block, [error],
[message])
Expects block not to throw an error, see assert.throws for details.
assert.ifError(value)
Tests if value is not a false value, throws if it is a true value. Useful when testing
the first argument, error in callbacks.
TTY
Use require('tty') to access this module.
Example:
tty.open(path, args=[])
Spawns a new process with the executable pointed to by path as the session
leader to a new pseudo terminal.
Returns an array [slaveFD, childProcess]. slaveFD is the file descriptor of
the slave end of the pseudo terminal. childProcess is a child process object.
tty.isatty(fd)
Returns true or false depending on if the fd is associated with a terminal.
tty.setRawMode(mode)
mode should be true or false. This sets the properties of the current process's
stdin fd to act either as a raw device or default.
tty.getWindowSize(fd)
Returns [row, col] for the TTY associated with the file descriptor.
os Module
Use require('os') to access this module.
os.hostname()
Returns the hostname of the operating system.
os.type()
Returns the operating system name.
os.release()
Returns the operating system release.
os.uptime()
Returns the system uptime in seconds.
os.loadavg()
Returns an array containing the 1, 5, and 15 minute load averages.
os.totalmem()
Returns the total amount of system memory in bytes.
os.freemem()
Returns the amount of free system memory in bytes.
os.cpus()
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).
Debugger
V8 comes with an extensive debugger which is accessible out-of-process via a
simple TCP protocol. Node has a built-in client for this debugger. To use this,
start Node with the debug argument; a prompt will appear:
At this point myscript.js is not yet running. To start the script, enter the
command run. If everything works okay, the output should look like this:
Node's debugger client doesn't support the full range of commands, but simple
step and inspection is possible. By putting the statement debugger; into the
source code of your script, you will enable a breakpoint.
For example, suppose myscript.js looked like this:
// myscript.js
x = 5;
setTimeout(function () {
debugger;
console.log("world");
}, 1000);
console.log("hello");
The print command allows you to evaluate variables. The next command steps
over to the next line. There are a few other commands available and more to come
type help to see others.
Advanced Usage
The V8 debugger can be enabled and accessed either by starting Node with
the --debug command-line flag or by signaling an existing Node process
with SIGUSR1.
Appendixes
Appendix 1 - Third Party Modules
There are many third party modules for Node. At the time of writing, August 2010,
the master repository of modules is the wiki page.