Você está na página 1de 161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

HOME DOWNLOAD ABOUT NPM REGISTRY DOC BLOG COMMUNITY LOGOS JOBS

Node.js v0.6.14 Manual & Documentation


Index View on single page View as JSON

C About this Documentation Stability Index JSON Output Synopsis Global Objects global process console Buffer require() require.resolve() require.cache __filename __dirname module exports setTimeout(cb, ms) clearTimeout(t) setInterval(cb, ms) clearInterval(t) console console.log() console.info() console.warn() console.error() console.dir(obj) console.time(label) console.timeEnd(label) console.trace() console.assert() Timers setTimeout(callback, delay, [arg], [...]) clearTimeout(timeoutId) setInterval(callback, delay, [arg], [...]) clearInterval(intervalId) Modules Cycles

@nodejs

nodej .o g/api/all.h ml

1/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Core Modules File Modules Loading from n d _ o u e Folders oemdls Folders as Modules Caching Module Caching Caveats The m d l Object oue module.exports module.require(id) module.id module.filename module.loaded module.parent module.children All Together... Loading from the global folders Accessing the main module Addenda: Package Manager Tips Addons Hello world Addon patterns Function arguments Callbacks Object factory Function factory Wrapping C++ objects Factory of wrapped objects Passing wrapped objects around process Event: 'exit' Event: 'uncaughtException' Signal Events process.stdout process.stderr process.stdin process.argv process.execPath process.chdir(directory) process.cwd() process.env process.exit([code]) process.getgid() process.setgid(id) process.getuid() process.setuid(id) process.version process.versions process.installPrefix process.kill(pid, [signal]) process.pid process.title

nodej .o g/api/all.h ml

2/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

process.arch process.platform process.memoryUsage() process.nextTick(callback) process.umask([mask]) process.uptime() util util.format() util.debug(string) util.log(string) util.inspect(object, [showHidden], [depth], [colors]) util.isArray(object) util.isRegExp(object) util.isDate(object) util.isError(object) util.pump(readableStream, writableStream, [callback]) util.inherits(constructor, superConstructor) Events Class: 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' Buffer Class: Buffer new Buffer(size) new Buffer(array) new Buffer(str, [encoding]) buf.write(string, [offset], [length], [encoding]) buf.toString([encoding], [start], [end]) buf[index] Class Method: Buffer.isBuffer(obj) Class Method: Buffer.byteLength(string, [encoding]) buf.length buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]) buf.slice([start], [end]) buf.readUInt8(offset, [noAssert]) buf.readUInt16LE(offset, [noAssert]) buf.readUInt16BE(offset, [noAssert]) buf.readUInt32LE(offset, [noAssert]) buf.readUInt32BE(offset, [noAssert]) buf.readInt8(offset, [noAssert]) buf.readInt16LE(offset, [noAssert]) buf.readInt16BE(offset, [noAssert]) buf.readInt32LE(offset, [noAssert]) buf.readInt32BE(offset, [noAssert])

nodej .o g/api/all.h ml

3/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

buf.readFloatLE(offset, [noAssert]) buf.readFloatBE(offset, [noAssert]) buf.readDoubleLE(offset, [noAssert]) buf.readDoubleBE(offset, [noAssert]) buf.writeUInt8(value, offset, [noAssert]) buf.writeUInt16LE(value, offset, [noAssert]) buf.writeUInt16BE(value, offset, [noAssert]) buf.writeUInt32LE(value, offset, [noAssert]) buf.writeUInt32BE(value, offset, [noAssert]) buf.writeInt8(value, offset, [noAssert]) buf.writeInt16LE(value, offset, [noAssert]) buf.writeInt16BE(value, offset, [noAssert]) buf.writeInt32LE(value, offset, [noAssert]) buf.writeInt32BE(value, offset, [noAssert]) buf.writeFloatLE(value, offset, [noAssert]) buf.writeFloatBE(value, offset, [noAssert]) buf.writeDoubleLE(value, offset, [noAssert]) buf.writeDoubleBE(value, offset, [noAssert]) buf.fill(value, [offset], [end]) buffer.INSPECT_MAX_BYTES Class: SlowBuffer Stream Readable Stream Event: 'data' Event: 'end' Event: 'error' Event: 'close' stream.readable stream.setEncoding(encoding) stream.pause() stream.resume() stream.destroy() stream.destroySoon() stream.pipe(destination, [options]) Writable Stream Event: 'drain' Event: 'error' Event: 'close' Event: 'pipe' stream.writable stream.write(string, [encoding], [fd]) stream.write(buffer) stream.end() stream.end(string, encoding) stream.end(buffer) stream.destroy() stream.destroySoon() Crypto crypto.createCredentials(details) crypto.createHash(algorithm) Class: Hash

nodej .o g/api/all.h ml

4/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

hash.update(data, [input_encoding]) hash.digest([encoding]) crypto.createHmac(algorithm, key) Class: Hmac hmac.update(data) hmac.digest([encoding]) crypto.createCipher(algorithm, password) crypto.createCipheriv(algorithm, key, iv) Class: Cipher cipher.update(data, [input_encoding], [output_encoding]) cipher.final([output_encoding]) crypto.createDecipher(algorithm, password) crypto.createDecipheriv(algorithm, key, iv) Class: Decipher decipher.update(data, [input_encoding], [output_encoding]) decipher.final([output_encoding]) crypto.createSign(algorithm) Class: Signer signer.update(data) signer.sign(private_key, [output_format]) crypto.createVerify(algorithm) Class: Verify verifier.update(data) verifier.verify(object, signature, [signature_format]) crypto.createDiffieHellman(prime_length) crypto.createDiffieHellman(prime, [encoding]) Class: DiffieHellman diffieHellman.generateKeys([encoding]) diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding]) diffieHellman.getPrime([encoding]) diffieHellman.getGenerator([encoding]) diffieHellman.getPublicKey([encoding]) diffieHellman.getPrivateKey([encoding]) diffieHellman.setPublicKey(public_key, [encoding]) diffieHellman.setPrivateKey(public_key, [encoding]) crypto.pbkdf2(password, salt, iterations, keylen, callback) crypto.randomBytes(size, [callback]) TLS (SSL) Client-initiated renegotiation attack mitigation NPN and SNI tls.createServer(options, [secureConnectionListener]) tls.connect(port, [host], [options], [secureConnectListener]) tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized]) Class: SecurePair Event: 'secure' Class: tls.Server Event: 'secureConnection' Event: 'clientError' server.listen(port, [host], [callback]) server.close() server.address()

nodej .o g/api/all.h ml

5/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

server.addContext(hostname, credentials) server.maxConnections server.connections Class: tls.CleartextStream Event: 'secureConnect' cleartextStream.authorized cleartextStream.authorizationError cleartextStream.getPeerCertificate() cleartextStream.address() cleartextStream.remoteAddress cleartextStream.remotePort File System fs.rename(path1, path2, [callback]) fs.renameSync(path1, path2) fs.truncate(fd, len, [callback]) fs.truncateSync(fd, len) fs.chown(path, uid, gid, [callback]) fs.chownSync(path, uid, gid) fs.fchown(fd, uid, gid, [callback]) fs.fchownSync(fd, uid, gid) fs.lchown(path, uid, gid, [callback]) fs.lchownSync(path, uid, gid) fs.chmod(path, mode, [callback]) fs.chmodSync(path, mode) fs.fchmod(fd, mode, [callback]) fs.fchmodSync(fd, mode) fs.lchmod(path, mode, [callback]) fs.lchmodSync(path, mode) fs.stat(path, [callback]) fs.lstat(path, [callback]) fs.fstat(fd, [callback]) fs.statSync(path) fs.lstatSync(path) fs.fstatSync(fd) fs.link(srcpath, dstpath, [callback]) fs.linkSync(srcpath, dstpath) fs.symlink(linkdata, path, [type], [callback]) fs.symlinkSync(linkdata, path, [type]) fs.readlink(path, [callback]) fs.readlinkSync(path) fs.realpath(path, [callback]) fs.realpathSync(path) fs.unlink(path, [callback]) fs.unlinkSync(path) fs.rmdir(path, [callback]) fs.rmdirSync(path) fs.mkdir(path, [mode], [callback]) fs.mkdirSync(path, [mode]) fs.readdir(path, [callback]) fs.readdirSync(path) fs.close(fd, [callback])

nodej .o g/api/all.h ml

6/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

fs.closeSync(fd) fs.open(path, flags, [mode], [callback]) fs.openSync(path, flags, [mode]) fs.utimes(path, atime, mtime, [callback]) fs.utimesSync(path, atime, mtime) fs.futimes(fd, atime, mtime, [callback]) fs.futimesSync(fd, atime, mtime) fs.fsync(fd, [callback]) fs.fsyncSync(fd) fs.write(fd, buffer, offset, length, position, [callback]) fs.writeSync(fd, buffer, offset, length, position) fs.writeSync(fd, str, position, [encoding]) fs.read(fd, buffer, offset, length, position, [callback]) fs.readSync(fd, buffer, offset, length, position) fs.readSync(fd, length, position, encoding) fs.readFile(filename, [encoding], [callback]) fs.readFileSync(filename, [encoding]) fs.writeFile(filename, data, [encoding], [callback]) fs.writeFileSync(filename, data, [encoding]) fs.watchFile(filename, [options], listener) fs.unwatchFile(filename) fs.watch(filename, [options], listener) Caveats Availability Filename Argument Class: fs.Stats fs.createReadStream(path, [options]) Class: fs.ReadStream Event: 'open' fs.createWriteStream(path, [options]) fs.WriteStream Event: 'open' file.bytesWritten Class: fs.FSWatcher watcher.close() Event: 'change' Event: 'error' Path path.normalize(p) path.join([path1], [path2], [...]) path.resolve([from ...], to) path.relative(from, to) path.dirname(p) path.basename(p, [ext]) path.extname(p) path.exists(p, [callback]) path.existsSync(p) net net.createServer([options], [connectionListener]) net.connect(arguments...) net.createConnection(arguments...)

nodej .o g/api/all.h ml

7/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Class: net.Server server.listen(port, [host], [listeningListener]) server.listen(path, [listeningListener]) server.close() server.address() server.maxConnections server.connections Event: 'listening' Event: 'connection' Event: 'close' Event: 'error' Class: net.Socket new net.Socket([options]) socket.connect(port, [host], [connectListener]) socket.connect(path, [connectListener]) socket.bufferSize socket.setEncoding([encoding]) socket.setSecure() socket.write(data, [encoding], [callback]) socket.write(data, [encoding], [callback]) socket.end([data], [encoding]) socket.destroy() socket.pause() socket.resume() socket.setTimeout(timeout, [callback]) socket.setNoDelay([noDelay]) socket.setKeepAlive([enable], [initialDelay]) socket.address() socket.remoteAddress socket.remotePort socket.bytesRead socket.bytesWritten Event: 'connect' Event: 'data' Event: 'end' Event: 'timeout' Event: 'drain' Event: 'error' Event: 'close' net.isIP(input) net.isIPv4(input) net.isIPv6(input) UDP / Datagram Sockets dgram.createSocket(type, [callback]) Class: Socket Event: 'message' Event: 'listening' Event: 'close' Event: 'error' dgram.send(buf, offset, length, port, address, [callback]) dgram.bind(port, [address])

nodej .o g/api/all.h ml

8/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

dgram.close() dgram.address() dgram.setBroadcast(flag) dgram.setTTL(ttl) dgram.setMulticastTTL(ttl) dgram.setMulticastLoopback(flag) dgram.addMembership(multicastAddress, [multicastInterface]) dgram.dropMembership(multicastAddress, [multicastInterface]) DNS dns.lookup(domain, [family], callback) dns.resolve(domain, [rrtype], callback) dns.resolve4(domain, callback) dns.resolve6(domain, callback) dns.resolveMx(domain, callback) dns.resolveTxt(domain, callback) dns.resolveSrv(domain, callback) dns.reverse(ip, callback) dns.resolveNs(domain, callback) dns.resolveCname(domain, callback) HTTP http.createServer([requestListener]) Class: http.Server Event: 'request' Event: 'connection' Event: 'close' Event: 'checkContinue' Event: 'upgrade' Event: 'clientError' server.listen(port, [hostname], [callback]) server.listen(path, [callback]) server.close() Class: http.ServerRequest Event: 'data' Event: 'end' Event: 'close' request.method request.url request.headers request.trailers request.httpVersion request.setEncoding([encoding]) request.pause() request.resume() request.connection Class: http.ServerResponse Event: 'close' response.writeContinue() response.writeHead(statusCode, [reasonPhrase], [headers]) response.statusCode response.setHeader(name, value) response.getHeader(name)

nodej .o g/api/all.h ml

9/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

response.removeHeader(name) response.write(chunk, [encoding]) response.addTrailers(headers) response.end([data], [encoding]) http.request(options, callback) http.get(options, callback) Class: http.Agent agent.maxSockets agent.sockets agent.requests http.globalAgent Class: http.ClientRequest Event 'response' Event: 'socket' Event: 'upgrade' Event: 'continue' request.write(chunk, [encoding]) request.end([data], [encoding]) request.abort() request.setTimeout(timeout, [callback]) request.setNoDelay([noDelay]) request.setSocketKeepAlive([enable], [initialDelay]) http.ClientResponse Event: 'data' Event: 'end' Event: 'close' response.statusCode response.httpVersion response.headers response.trailers response.setEncoding([encoding]) response.pause() response.resume() HTTPS Class: https.Server https.createServer(options, [requestListener]) https.request(options, callback) https.get(options, callback) Class: https.Agent https.globalAgent URL url.parse(urlStr, [parseQueryString], [slashesDenoteHost]) url.format(urlObj) url.resolve(from, to) Query String querystring.stringify(obj, [sep], [eq]) querystring.parse(str, [sep], [eq]) querystring.escape querystring.unescape Readline rl.createInterface(input, output, completer)

nodej .o g/api/all.h ml

10/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Class: Interface rl.setPrompt(prompt, length) rl.prompt() rl.question(query, callback) rl.close() rl.pause() rl.resume() rl.write() Event: 'line' Event: 'close' REPL repl.start([prompt], [stream], [eval], [useGlobal], [ignoreUndefined]) REPL Features Executing JavaScript vm.runInThisContext(code, [filename]) vm.runInNewContext(code, [sandbox], [filename]) vm.runInContext(code, context, [filename]) vm.createContext([initSandbox]) vm.createScript(code, [filename]) Class: Script script.runInThisContext() script.runInNewContext([sandbox]) Child Process Class: ChildProcess Event: 'exit' child.stdin child.stdout child.stderr child.pid child.kill([signal]) child.send(message, [sendHandle]) child_process.spawn(command, [args], [options]) child_process.exec(command, [options], callback) child_process.execFile(file, args, options, callback) child_process.fork(modulePath, [args], [options]) Assert assert.fail(actual, expected, message, operator) assert(value, message), assert.ok(value, [message]) assert.equal(actual, expected, [message]) assert.notEqual(actual, expected, [message]) assert.deepEqual(actual, expected, [message]) assert.notDeepEqual(actual, expected, [message]) assert.strictEqual(actual, expected, [message]) assert.notStrictEqual(actual, expected, [message]) assert.throws(block, [error], [message]) assert.doesNotThrow(block, [error], [message]) assert.ifError(value) TTY tty.isatty(fd) tty.setRawMode(mode) Zlib

nodej .o g/api/all.h ml

11/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Examples Constants zlib.createGzip([options]) zlib.createGunzip([options]) zlib.createDeflate([options]) zlib.createInflate([options]) zlib.createDeflateRaw([options]) zlib.createInflateRaw([options]) zlib.createUnzip([options]) Class: zlib.Gzip Class: zlib.Gunzip Class: zlib.Deflate Class: zlib.Inflate Class: zlib.DeflateRaw Class: zlib.InflateRaw Class: zlib.Unzip Convenience Methods zlib.deflate(buf, callback) zlib.deflateRaw(buf, callback) zlib.gzip(buf, callback) zlib.gunzip(buf, callback) zlib.inflate(buf, callback) zlib.inflateRaw(buf, callback) zlib.unzip(buf, callback) Options Memory Usage Tuning os os.hostname() os.type() os.platform() os.arch() os.release() os.uptime() os.loadavg() os.totalmem() os.freemem() os.cpus() os.networkInterfaces() Debugger Watchers Commands reference Stepping Breakpoints Info Execution control Various Advanced Usage Cluster cluster.fork() cluster.isMaster cluster.isWorker

nodej .o g/api/all.h ml

12/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Event: 'death' Appendix 1 - Third Party Modules

The goal of this documentation is to comprehensively explain the Node.js API, both from a reference as well as conceptual point of view. Each section describes a built-in module or high-level concept. Where appropriate, property types, method arguments, and the arguments provided to event handlers are detailed in a list underneath the topic heading.

Every . t l document has a corresponding . s n document presenting the same information in a structure hm jo manner. This feature is experimental, and added for the benefit of IDEs and other utilities that wish to do programmatic things with the documentation. Every . t l and . s n file is generated based on the corresponding . a k o n file in the d c a i hm jo mrdw o/p/ node's source tree. The documentation is generated using the t o s d c g n r t . s program. The HTML ol/o/eeaej template is located at d c t m l t . t l. o/epaehm

Throughout the documentation, you will see indications of a section's stability. The Node.js API is still somewha changing, and as it matures, certain parts are more reliable than others. Some are so proven, and so relied upo that they are unlikely to ever change at all. Others are brand new and experimental, or known to be hazardous and in the process of being redesigned. The notices look like this:
Saiiyxeietl tblt:1Eprmna

The stability indices are as follows: 0 - Deprecated This feature is known to be problematic, and changes are planned. Do not rely on it. of the feature may cause warnings. Backwards compatibility should not be expected.

1 - E perimental This feature was introduced recently, and may change or be removed in future version Please try it out and provide feedback. If it addresses a use-case that is important to you, tell the node cor team. 2 - Unstable The API is in the process of settling, but has not yet had sufficient real-world testing to be considered stable. Backwards-compatibility will be maintained if reasonable.

3 - Stable The API has proven satisfactory, but cleanup in the underlying code may cause minor change Backwards-compatibility is guaranteed.

4 - API Fro en This API has been tested extensively in production and is unlikely to ever have to change

5 - Locked Unless serious bugs are found, this code will not ever change. Please do not suggest changes i this area; they will be refused.

nodej .o g/api/all.h ml

13/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

JSONO
Saiiyxeietl tblt:1Eprmna

Every HTML file in the markdown has a corresponding JSON file with the same data. This feature is new as of node v0.6.12. It is experimental.

S
An example of a web server written with Node which responds with 'Hello World':
vrhteur(ht' atp=rqie'tp) ht.raeevrfntorqetepne tpcetSre(ucin(eus,rsos){ rsos.rtHa(0,{CnetTp'tx/li') epnewieed20'otnye:'etpan} rsos.n(HloWrdn) epneed'elol\' }.itn82) )lse(14 cnoelg'evrrnigatp/1700182/) osl.o(Sreunntht:/2...:14'

To run the server, put the code into a file called e a p e j and execute it with the node program xml.s
>ndxml.s oeeapej Sreunntht:/2...:14 evrrnigatp/1700182/

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

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

{Object} 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
s m t i g will define a global variable. In Node this is different. The top-level scope is not the global scope; oehn s m t i g inside a Node module will be local to that module. oehn

{Object}

nodej .o g/api/all.h ml

14/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The process object. See the process object section.

{Object} Used to print to stdout and stderr. See the stdio section.

B
{Object} Used to handle binary data. See the buffer section.

()
{Function} To require modules. See the Modules section. r q i e isn't actually a global but rather local to each module. eur

()

Use the internal r q i e ) machinery to look up the location of a module, but rather than loading the modul eur( just return the resolved filename.

.
Object Modules are cached in this object when they are required. By deleting a key value from this object, the next r q i e will reload the module. eur

__
{String}

The filename of the code being executed. This is the resolved absolute path of this code file. For a main program this is not necessarily the same filename used in the command line. The value inside a module is the path to tha module file. Example: running n d x m l . s from / s r / j oeeapej Uesmr
cnoelg_flnm) osl.o(_ieae /Uesmreapej //sr/j/xml.s

_ f l n m isn't actually a global but rather local to each module. _ieae

nodej .o g/api/all.h ml

15/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

__
{String} The name of the directory that the currently executing script resides in. Example: running n d x m l . s from / s r / j oeeapej Uesmr
cnoelg_drae osl.o(_inm) /Uesmr //sr/j

_ d r a e isn't actually a global but rather local to each module. _inm

{Object} A reference to the current module. In particular m d l . x o t is the same as the e p r s object. See oueeprs xot
s c n d . s for more information. m d l isn't actually a global but rather local to each module. r/oej oue

An object which is shared between all instances of the current module and made accessible through r q i e ) eur(
e p r s is the same as the m d l . x o t object. See s c n d . s for more information. e p r s xot oueeprs r/oej xot

actually a global but rather local to each module. See the module system documentation for more information. See the module section for more information.

T T I I (

, () , () )

The timer functions are global variables. See the timers section.

SaiiyPrzn tblt:4AIFoe

{Object}

For printing to stdout and stderr. Similar to the console object functions provided by most web browsers, here t

nodej .o g/api/all.h ml

16/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

output is sent to stdout or stderr.

()

Prints to stdout with newline. This function can take multiple arguments in a p i t ( -like way. Example: rnf)
cnoelg'on:%'on) osl.o(cutd,cut

If formatting elements are not found in the first string then u i . n p c is used on each argument. See tliset util.format() for more information.

()

Same as c n o e l g. osl.o

. .

() ()

Same as c n o e l g but prints to stderr. osl.o

Uses u i . n p c on o j and prints resulting string to stderr. tliset b

.
Mark a time.

Finish timer, record output. Example


cnoetm(10eeet' osl.ie'0lmns) fr(ai<10+){ ovri=00i+ } cnoetmEd'0lmns) osl.ien(10eeet'

()

Print a stack trace to stderr of the current position.

.
Same as a s r . k ). seto(

()

nodej .o g/api/all.h ml

17/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

T
Saiiyokd tblt:5Lce

All of the timer functions are globals. You do not need to r q i e ) this module in order to use them. eur(

,[

],[...])

To schedule execution of a one-time c l b c after d l y milliseconds. Returns a t m o t d for possible us alak ea ieuI with c e r i e u ( . Optionally you can also pass arguments to the callback. laTmot) It is important to note that your callback will probably not be called in exactly d l y milliseconds - Node.js ea

makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in The callback will be called as close as possible to the time specified.

I )

Prevents a timeout from triggering.

,[

],[...])

To schedule the repeated execution of c l b c every d l y milliseconds. Returns a i t r a I for possibl alak ea nevld use with c e r n e v l ). Optionally you can also pass arguments to the callback. laItra(

I )

Stops a interval from triggering.

M
Saiiyokd tblt:5Lce

Node has a simple module loading system. In Node, files and modules are in one-to-one correspondence. example, f o j loads the module c r l . s in the same directory. o.s icej The contents of f o j : o.s
vrcrleur(.crl.s) aice=rqie'/icej' cnoelgTeaefacrlfrdus' osl.o('hraoiceoais4i iceae() +crl.ra4)

The contents of c r l . s: icej


vrPahP aI=Mt.I

nodej .o g/api/all.h ml

18/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

eprsaeucin(){ xot.ra=fntor rtrI*r*r eunP } eprscrufrne=fntor xot.icmeecucin(){ rtrI*r eun2*P }

The module c r l . s has exported the functions a e ( and c r u f r n e ). To export an object, add icej ra) icmeec( the special e p r s object. xot Variables local to the module will be private. In this example the variable P is private to c r l . s. I icej The module system is implemented in the r q i e " o u e ) module. eur(mdl"

C
When there are circular r q i e ) calls, a module might not be done being executed when it is returned. eur( Consider this situation:
aj : .s

cnoelg'trig) osl.o(asatn' eprsdnas xot.oe=fle vrb=rqie'/.s) aeur(.bj' cnoelg'na.oe=%'.oe osl.o(i,bdnj,bdn) eprsdnre xot.oe=tu cnoelg'oe) osl.o(adn'

bj : .s

cnoelg'trig) osl.o(bsatn' eprsdnas xot.oe=fle vra=rqie'/.s) aeur(.aj' cnoelg'nb.oe=%'.oe osl.o(i,adnj,adn) eprsdnre xot.oe=tu cnoelg'oe) osl.o(bdn'

mi.s anj :

cnoelg'ansatn' osl.o(mitrig) vra=rqie'/.s) aeur(.aj' vrb=rqie'/.s) aeur(.bj' cnoelg'nmi,adn=j.oe%'.oe.oe osl.o(ian.oe%,bdn=j,adn,bdn)

When m i . s loads a j , then a j in turn loads b j . At that point, b j tries to load a j . In order t anj .s .s .s .s .s

nodej .o g/api/all.h ml

19/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

prevent an infinite loop an unfinished cop of the a j exports object is returned to the b j module. .s .s then finishes loading, and its exports object is provided to the a j module. .s

By the time m i . s has loaded both modules, they're both finished. The output of this program would thus b anj
$ndanj oemi.s mitrig ansatn asatn trig bsatn trig i,adnas nb.oe=fle bdn oe i,bdnre na.oe=tu adn oe ian.oetu,bdn=re nmi,adn=re.oetu

If you have cyclic module dependencies in your program, make sure to plan accordingly.

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 l b folder. i/ Core modules are always preferentially loaded if their identifier is passed to r q i e ). For instance, eur(
r q i e ' t p ) will always return the built in HTTP module, even if there is a file by that name. eur(ht'

F M

If the exact filename is not found, then node will attempt to load the required filename with the added extensio of . s, . s n, and then . o e. j jo nd

. s files are interpreted as JavaScript text files, and . s n files are parsed as JSON text files. . o e files are j jo nd

interpreted as compiled addon modules loaded with d o e . lpn A module prefixed with ' ' is an absolute path to the file. For example, r q i e ' h m / a c / o . s ) / eur(/oemrofoj' load the file at / o e m r o f o j . hm/ac/o.s

A module prefixed with ' / is relative to the file calling r q i e ). That is, c r l . s must be in the same .' eur( icej directory as f o j for r q i e ' / i c e ) to find it. o.s eur(.crl' Without a leading '/' or './' to indicate a file, the module is either a "core module" or is loaded from a n d _ o u e folder. oemdls

n d _ o u e F oemdls

If the module identifier passed to r q i e ) is not a native module, and does not begin with ' ', ' . ' eur( / ./

' / , then node starts at the parent directory of the current module, and adds / o e m d l s and attempts .' nd_oue ,

nodej .o g/api/all.h ml

20/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

to load the module from that location. If it is not found there, then it moves to the parent directory, and so on, until the root of the tree is reached.

For example, if the file at ' h m / y p o e t / o . s called r q i e ' a . s ), then node would look i /oer/rjcsfoj' eur(brj' the following locations, in this order:
/oer/rjcsnd_oue/a.s hm/ypoet/oemdlsbrj /oer/oemdlsbrj hm/ynd_oue/a.s /oend_oue/a.s hm/oemdlsbrj /oemdlsbrj nd_oue/a.s

This allows programs to localize their dependencies, so that they do not clash.

It is convenient to organize programs and libraries into self-contained directories, and then provide a single ent point to that library. There are three ways in which a folder may be passed to r q i e ) as an argument. eur(

The first is to create a p c a e j o file in the root of the folder, which specifies a m i module. An example akg.sn an package.json file might look like this:
{"aesmirr" nm":"oelbay, "an.lbsmirr.s mi":"/i/oelbayj"}

If this was in a folder at . s m i r r , then r q i e ' / o e l b a y ) would attempt to load /oelbay eur(.smirr'
lbaylbsmirr.s irr/i/oelbayj .

This is the extent of Node's awareness of package.json files. If there is no package.json file present in the directory, then node will attempt to load an i d x j or ne.s
r q i e ' / o e l b a y ) would attempt to load: eur(.smirr' .smirr/ne.s /oelbayidxj .smirr/ne.oe /oelbayidxnd

i d x n d file out of that directory. For example, if there was no package.json file in the above example, then ne.oe

C
Modules are cached after the first time they are loaded. This means (among other things) that every call to r q i e ' o ' will get exactly the same object returned, if it would resolve to the same file. eur(fo) Multiple calls to r q i e ' o ' may not cause the module code to be executed multiple times. This is an eur(fo)

important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles. If you want to have a module execute code multiple times, then export a function, and call that function.

nodej .o g/api/all.h ml

21/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Modules are cached based on their resolved filename. Since modules may resolve to a different filename based the location of the calling module (loading from n d _ o u e folders), it is not a guarantee that oemdls
r q i e ' o ' will always return the exact same object, if it would resolve to different files. eur(fo)

m d l O oue
{Object}

In each module, the m d l free variable is a reference to the object representing the current module. In oue particular m d l . x o t is the same as the e p r s object. m d l isn't actually a global but rather local oueeprs xot oue each module.

.
Object

The e p r s object is created by the Module system. Sometimes this is not acceptable, many want their modul xot to be an instance of some class. To do this assign the desired export object to m d l . x o t . For example oueeprs suppose we were making a module called a j .s
vrEetmteeur(eet'.vnEitr avnEitr=rqie'vns)Eetmte mdl.xotevnEitr) oueeprs=nwEetmte( /osmoknfeoetmmt /Doewr,adatrsmieei /hrayvnrmtemdltef /te'ed'eetfohoueisl. stieu(ucin){ eTmotfnto( mdl.xot.mt'ed' oueeprsei(ray) }00 ,10)

Then in another file we could do


vra=rqie'/' aeur(.a) ao(ray,fnto( .n'ed'ucin){ cnoelg'oueaied' osl.o(mdlsray) } )

Note that assignment to m d l . x o t must be done immediately. It cannot be done in any callbacks. oueeprs does not work: x.js:
stieu(ucin){ eTmotfnto( mdl.xot:"el"} oueeprs={ahlo }) ,0

nodej .o g/api/all.h ml

22/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

y.js:
vrx=rqie'/' aeur(.x) cnoelgxa osl.o(.)

.
i String d

( )

Return: Object e p r sfrom the resolved module xot The m d l . e u r method provides a way to load a module as if r q i e ) was called from the original ouerqie eur( module. Note that in order to do this, you must get a reference to the m d l object. Since r q i e ) returns the oue eur(
e p r s and the m d l is typically onl available within a specific module's code, it must be explicitly xot , oue

exported in order to be used.

.
String The identifier for the module. Typically this is the fully resolved filename.

.
String The fully resolved filename to the module.

.
Boolean Whether or not the module is done loading, or is in the process of loading.

.
Module Object The module that required this one.

.
Array

nodej .o g/api/all.h ml

23/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The module objects required by this one.

A T

...

To get the exact filename that will be loaded when r q i e ) is called, use the r q i e r s l e ) function eur( eur.eov( Putting together all of the above, here is the high-level algorithm in pseudocode of what require.resolve does:
rqieXrmmdltpt eur()fooueaahY 1fXioemdl, .Isacroue .rtrhoemdl aeuntecroue .SO bTP 2fXbgnih'/r''o./ .Ieiswt.'o/r'.' .LA_SFL() aODA_IEY+X .LA_SDRCOYY+X bODA_IETR() 3ODND_OUE(,draeY) .LA_OEMDLSXinm() 4HOntfud .TRW"oon" LA_SFL() ODA_IEX 1fXiieodXaaacittx.TP .Isafl,lasJvSrpetSO 2fXjsafl,la.saaacittx.TP .I.siieodXjsJvSrpetSO 3fXndsafl,la.oeaiayadnSO .I.oeiieodXndsbnrdo.TP LA_SDRCOYX ODA_IETR() 1fXpcaejosafl, .I/akg.sniie .PreXpcaejo,adloomi"fed aas/akg.snnokfr"anil. .ltM=X+(snmiil) bejoanfed .LA_SFL() cODA_IEM 2fXidxjsafl,la/ne.saaacittx.TP .I/ne.siieodXidxjsJvSrpetSO 3fXidxndsafl,la/ne.oeaiayadnSO .I/ne.oeiieodXidxndsbnrdo.TP LA_OEMDLSXTR) ODND_OUE(,SAT 1eISND_OUE_AH(TR) .ltDR=OEMDLSPTSSAT 2oahDRiIS .frecInDR: .LA_SFL(I/) aODA_IEDRX .LA_SDRCOYDRX bODA_IETR(I/) ND_OUE_AH(TR) OEMDLSPTSSAT 1eATahsltSAT .ltPRS=ptpi(TR) 2eOT=idxoisntneond_oue"iAT,o .ltROneffrtisacf"oemdlsnPRSr0 3eonfPRS1 .ltI=cutoAT 4eIS=[ .ltDR] 5hlOT .wieI>RO, .iAT[]="oemdlsOTNE afPRSInd_oue"CNIU .DR=ptonPRS0.]+"oemdls) cIahji(AT[.Ind_oue" .DRIS+DR bIS=DRI .ltI=I1 ce 6eunDR .rtrIS

nodej .o g/api/all.h ml

24/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

If the N D _ A H environment variable is set to a colon-delimited list of absolute paths, then node will search OEPT those paths for modules if they are not found elsewhere. (Note: On Windows, N D _ A H is delimited by OEPT semicolons instead of colons.) Additionally, node will search in the following locations: 1: $ O E . o e m d l s HM/nd_oue 2: $ O E . o e l b a i s HM/nd_irre 3: $ R F X l b n d PEI/i/oe Where $ O E is the user's home directory, and $ R F X is node's configured i s a l r f x. HM PEI ntlPei These are mostly for historic reasons. You are highly encouraged to place your dependencies locally in n d _ o u e folders. They will be loaded faster, and more reliably. oemdls

When a file is run directly from Node, r q i e m i is set to its m d l . That means that you can determine eur.an oue whether a file has been run directly by testing
rqiemi=oue eur.an==mdl

For a file f o j , this will be t u if run via n d o . s, but f l e if run by r q i e ' / o ' . o.s re oefoj as eur(.fo) Because m d l provides a f l n m property (normally equivalent to _ f l n m ), the entry point of the oue ieae _ieae current application can be obtained by checking r q i e m i . i e a e. eur.anflnm

:P

The semantics of Node's r q i e ) function were designed to be general enough to support a number of sane eur( build native packages from Node modules without modification. Below we give a suggested directory structure that could work: Let's say that we wanted to have the folder at / s / i / o e < o e p c a e / s m e s o > hold the urlbnd/smakg><oevrin contents of a specific version of a package.

directory structures. Package manager programs such as d k , r m, and n m will hopefully find it possible to pg p p

Packages can depend on one another. In order to install package f o, you may have to install a specific versio o of package b r. The b r package may itself have dependencies, and in some cases, these dependencies may a a even collide or form cycles.

Since Node looks up the r a p t of any modules it loads (that is, resolves symlinks), and then looks for their elah dependencies in the n d _ o u e folders as described above, this situation is very simple to resolve with the oemdls following architecture:
/ s / i / o e f o 1 2 3 - Contents of the f opackage, version 1.2.3. urlbnd/o/../ o / s / i / o e b r 4 3 2 - Contents of the b rpackage that f odepends on. urlbnd/a/../ a o

nodej .o g/api/all.h ml

25/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

/ s / i / o e f o 1 2 3 n d _ o u e / a - Symbolic link to / s / i / o e b r 4 3 2 . urlbnd/o/../oemdlsbr urlbnd/a/../ / s / i / o e b r 4 3 2 n d _ o u e / - Symbolic links to the packages that b rdepends on. urlbnd/a/../oemdls* a

Thus, even if a cycle is encountered, or if there are dependency conflicts, every module will be able to get a version of its dependency that it can use. When the code in the f o package does r q i e ' a ' , it will get the version that is symlinked into o eur(br)
/ s / i / o e f o 1 2 3 n d _ o u e / a . Then, when the code in the b r package calls urlbnd/o/../oemdlsbr a

r q i e ' u x ) it'll get the version that is symlinked into / s / i / o e b r 4 3 2 n d _ o u e / u x eur(qu' , urlbnd/a/../oemdlsqu

Furthermore, to make the module lookup process even more optimal, rather than putting packages directly in / s / i / o e we could put them in / s / i / o e m d l s < a e / v r i n . Then node will not urlbnd , urlbnd_oue/nm><eso> bother looking for missing dependencies in / s / o e m d l s or / o e m d l s. urnd_oue nd_oue In order to make modules available to the node REPL, it might be useful to also add the / s / i / o e m d l s folder to the $ O E P T environment variable. Since the module lookups using urlbnd_oue ND_AH
n d _ o u e folders are all relative, and based on the real path of the files making the calls to r q i e ) oemdls eur(

packages themselves can be anywhere.

A
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:

V8 JavaScript, a C++ library. Used for interfacing with JavaScript: creating objects, calling functions, etc. Documented mostly in the v . header file ( d p / 8 i c u e v . in the Node source tree), which is 8h esv/nld/8h

also available online. libuv, C event loop library. Anytime one needs to wait for a file descriptor to become readable, wait for a timer, or wait for a signal to received one will need to interface with libuv. That is, if you perform any I/O, libuv will need to be used. Internal Node libraries. Most importantly is the n d : O j c W a class which you will likely want to oe:betrp derive from. Others. Look in d p / for what else is available. es

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

To get started let's make a small Addon which is the C++ equivalent of the following Javascript code:
eprshlo=fnto(eun'ol' xot.elucin){rtrwrd}

First we create a file h l o c : el.c


#nldnd.> icue<oeh #nldv.> icue<8h

nodej .o g/api/all.h ml

26/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

uignmsaev snaepc8 Hnl<au>Mto(osruet&ag){ adeVleehdcntAgmnsrs HnlSoesoe adecpcp rtrcp.ls(tig:e(wrd) eunsoeCoeSrn:Nw"ol") } vintHnl<betagt odii(adeOjc>tre){ treStSrn:Nwybl"el", agt>e(tig:eSmo(hlo) FntoTmlt:NwMto)>eFnto() ucinepae:e(ehdGtucin) } ND_OUEhlont OEMDL(el,ii)

Note that all Node addons must export an initialization function:


vintaie(adeOjc>tre) odIiilzHnl<betagt ND_OUEmdl_aentaie OEMDL(ouenm,Iiilz)

There is no semi-colon after N D _ O U E as it's not a function (see n d . ). OEMDL oeh The m d l _ a e needs to match the filename of the final binary (minus the .node suffix). ouenm The source code needs to be built into h l o n d , the binary Addon. To do this we create a file called el.oe which is python code and looks like this:
sci. rdr='' bdibid ldr='ul' VRIN='..' ESO001 dfstotosot: ee_pin(p) otto_pin(cmie_x' p.olotos'oplrcx) dfcniuecn) eofgr(of: cn.hc_ol'oplrcx) ofcekto(cmie_x' cn.hc_ol'oeadn) ofcekto(nd_do' dfbidbd: eul(l) oj=bdnwts_e(cx,'hi'nd_do' bl.e_akgn'x'slb,'oeadn) ojtrehlo b.agt='el' ojsuchloc' b.ore='el.c

Running n d a o f g r u l will create a file b i d d f u t h l o n d which is our Addon. oewfcniuebid ul/eal/el.oe


n d a is just WAF, the python-based build system. n d a is provided for the ease of users. oewf oewf

You can now use the binary addon in a Node project h l o j by pointing r q i e to the recently built el.s eur module:
vradn=rqie'/ul/ees/el' adoeur(.bidRlaehlo)

nodej .o g/api/all.h ml

27/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelgadnhlo)/wrd osl.o(do.el()/'ol'

Please see patterns below for further information or https://github.com/pietern/hiredis-node for an example in production.

Below are some addon patterns to help you get started. Consult the online v8 reference for help with the variou v8 calls, and v8's Embedder's Guide for an explanation of several concepts used such as handles, scopes, function templates, etc. To compile these examples, create the w c i t file below and run n d a o f g r u l : srp oewfcniuebid
sci. rdr='' bdibid ldr='ul' VRIN='..' ESO001 dfstotosot: ee_pin(p) otto_pin(cmie_x' p.olotos'oplrcx) dfcniuecn) eofgr(of: cn.hc_ol'oplrcx) ofcekto(cmie_x' cn.hc_ol'oeadn) ofcekto(nd_do' dfbidbd: eul(l) oj=bdnwts_e(cx,'hi'nd_do' bl.e_akgn'x'slb,'oeadn) ojtreadn b.agt='do' ojsuc'do.c] b.ore=[adnc'

In cases where there is more than one . c file, simply add the file name to the o j s u c array, e.g.: c b.ore
ojsuc'do.c,'yxml.c] b.ore=[adnc'meapec'

The following pattern illustrates how to read arguments from JavaScript function calls and return a result. Thi is the main and only needed source a d n c : do.c
#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh uignmsaev snaepc8 Hnl<au>AdcntAgmnsrs adeVled(osruet&ag){ HnlSoesoe adecpcp

nodej .o g/api/all.h ml

28/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

iag.egh)<2 f(rsLnt(){ Trwxeto(xeto:TpErrSrn:Nw"rnubroruet") hoEcpinEcpin:yero(tig:e(Wognmefagmns)) rtrcp.ls(neie() eunsoeCoeUdfnd) } i!rs0INme(|!rs1INme(){ f(ag[]>subr)|ag[]>subr) Trwxeto(xeto:TpErrSrn:Nw"rnruet") hoEcpinEcpin:yero(tig:e(Wogagmns)) rtrcp.ls(neie() eunsoeCoeUdfnd) } LclNme>nm=Nme:Nwag[]>ubrau( oa<ubruubr:e(rs0NmeVle)+ ag[]>ubrau() rs1NmeVle) rtrcp.ls(u) eunsoeCoenm } vintHnl<betagt odIi(adeOjc>tre){ treStSrn:Nwybl"d", agt>e(tig:eSmo(ad) FntoTmlt:NwAdGtucin) ucinepae:e(d)>eFnto() } ND_OUEadnnt OEMDL(do,Ii)

You can test it with the following JavaScript snippet:


vradn=rqie'/ul/ees/do' adoeur(.bidRlaeadn) cnoelgTihudbih:,adnad35 osl.o('hssoleegt'do.d(,))

C
You can pass JavaScript functions to a C++ function and execute them from there. Here's a d n c : do.c
#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh uignmsaev snaepc8 Hnl<au>RnalakcntAgmnsrs adeVleuClbc(osruet&ag){ HnlSoesoe adecpcp LclFnto>coa<ucin:Cs(rs0) oa<ucinb=LclFnto>:atag[] cntusgerc=1 osnindag LclVlervag]={LclVle:NwSrn:Nw"elol")} oa<au>ag[rcoa<au>:e(tig:e(hlowrd) cCl(otx:Gturn(Goa(,ag,ag) b>alCnet:eCret)>lbl)rcrv rtrcp.ls(neie() eunsoeCoeUdfnd) } vintHnl<betagt odIi(adeOjc>tre){ treStSrn:Nwybl"uClbc", agt>e(tig:eSmo(rnalak)

nodej .o g/api/all.h ml

29/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

FntoTmlt:NwRnalakGtucin) ucinepae:e(uClbc)>eFnto() } ND_OUEadnnt OEMDL(do,Ii)

To test it run the following JavaScript snippet:


vradn=rqie'/ul/ees/do' adoeur(.bidRlaeadn) adnrnalakfnto(s) do.uClbc(ucinmg{ cnoelgmg/hlowrd osl.o(s)/'elol' } )

You can create and return new objects from within a C++ function with this a d n c pattern, which returns do.c an object with property m g that echoes the string passed to c e t O j c ( : s raebet)
#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh uignmsaev snaepc8 Hnl<au>CetOjc(osruet&ag){ adeVleraebetcntAgmnsrs HnlSoesoe adecpcp LclOjc>oj=Ojc:Nw) oa<betbbet:e( oj>e(tig:eSmo(mg)rs0TSrn() bStSrn:Nwybl"s",ag[]>otig) rtrcp.ls(b) eunsoeCoeoj } vintHnl<betagt odIi(adeOjc>tre){ treStSrn:Nwybl"raebet) agt>e(tig:eSmo(cetOjc", FntoTmlt:NwCetOjc)>eFnto() ucinepae:e(raebetGtucin) } ND_OUEadnnt OEMDL(do,Ii)

To test it in JavaScript:
vradn=rqie'/ul/ees/do' adoeur(.bidRlaeadn) vrojdo.raebet'el' ab1=adncetOjc(hlo) vrojdo.raebet'ol' ab2=adncetOjc(wrd) cnoelgoj.s++b2mg/hlowrd osl.o(b1mg''oj.s)/'elol'

nodej .o g/api/all.h ml

30/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

This pattern illustrates how to create and return a JavaScript function that wraps a C++ function:
#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh uignmsaev snaepc8 Hnl<au>MFnto(osruet&ag){ adeVleyucincntAgmnsrs HnlSoesoe adecpcp rtrcp.ls(tig:e(hlowrd) eunsoeCoeSrn:Nw"elol") } Hnl<au>CetFnto(osruet&ag){ adeVleraeucincntAgmnsrs HnlSoesoe adecpcp LclFntoTmlt>tl=FntoTmlt:NwMFnto) oa<ucinepaepucinepae:e(yucin LclFnto>fpGtucin) oa<ucinn=tl>eFnto( fStaeSrn:Nwybl"hFnto")/oihstaeinnmu n>eNm(tig:eSmo(teucin)/mttiomktaoyos rtrcp.ls(n eunsoeCoef) } vintHnl<betagt odIi(adeOjc>tre){ treStSrn:Nwybl"raeucin) agt>e(tig:eSmo(cetFnto", FntoTmlt:NwCetFnto)>eFnto() ucinepae:e(raeucinGtucin) } ND_OUEadnnt OEMDL(do,Ii)

To test:
vradn=rqie'/ul/ees/do' adoeur(.bidRlaeadn) vrfdo.raeucin) an=adncetFnto( cnoelgf()/'elol' osl.o(n)/hlowrd

C++

Here we will create a wrapper for a C++ object/class M O j c that can be instantiated in JavaScript through ybet the n w operator. First prepare the main module a d n c : e do.c
#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh #nldmojc." icue"ybeth uignmsaev snaepc8 vintl(adeOjc>tre){ odIiAlHnl<betagt

nodej .o g/api/all.h ml

31/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

MOjc:Ii(agt ybet:nttre) } ND_OUEadnntl) OEMDL(do,IiAl

Then in m o j c . make your wrapper inherit from n d : O j c W a : ybeth oe:betrp


#fdfMOJC_ ineYBETH #eieMOJC_ dfnYBETH #nldnd.> icue<oeh casMOjculcnd:OjcWa lsybet:pbioe:betrp{ ulc pbi: saiodIi(8:adev:Ojc>tre) ttcvintv:Hnl<8:betagt rvt: piae MOjc( ybet) ~ybet) MOjc( sai8:adev:Vlee(os8:ruet&ag) ttcv:Hnl<8:au>Nwcntv:Agmnsrs sai8:adev:Vlelsn(os8:ruet&ag) ttcv:Hnl<8:au>PuOecntv:Agmnsrs dulone_ obecutr } #ni edf

And in m o j c . c implement the various methods that you want to expose. Here we expose the method ybetc
p u O e by adding it to the constructor's prototype: lsn

#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh #nldmojc." icue"ybeth uignmsaev snaepc8 MOjc:MOjc(} ybet:ybet){ MOjc:~ybet){ ybet:MOjc(} viybet:ntHnl<betagt odMOjc:Ii(adeOjc>tre){ /rprosrcoepae /Peaecntutrtmlt LclFntoTmlt>tl=FntoTmlt:NwNw oa<ucinepaepucinepae:e(e) tl>eCasaeSrn:Nwybl"ybet) pStlsNm(tig:eSmo(MOjc") tl>ntneepae)>eItraFedon() pIsacTmlt(StnenlilCut1 /rttp /Pooye tl>rttpTmlt(StSrn:Nwybl"lsn", pPooyeepae)>e(tig:eSmo(puOe) FntoTmlt:NwPuOeGtucin) ucinepae:e(lsn)>eFnto() Pritn<ucinosrcoessetFnto>:e(pGtucin) essetFnto>cntutr=Pritn<ucin:Nwtl>eFnto() treStSrn:Nwybl"ybet)osrco) agt>e(tig:eSmo(MOjc",cntutr }

nodej .o g/api/all.h ml

32/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Hnl<au>MOjc:NwcntAgmnsrs adeVleybet:e(osruet&ag){ HnlSoesoe adecpcp MOjc*oj=nwMOjc( ybetbeybet) oj>one_=ag[]>sneie(rs0NmeVle) bcutrrs0IUdfnd)?0:ag[]>ubrau( oj>rpag.hs) bWa(rsTi() rtrrsTi( eunag.hs) } Hnl<au>MOjc:PuOecntAgmnsrs adeVleybet:lsn(osruet&ag){ HnlSoesoe adecpcp MOjc*oj=OjcWa:Uwa<ybet(rsTi() ybetbbetrp:nrpMOjc>ag.hs) oj>one_+ bcutr=1 rtrcp.ls(ubr:e(bcutr) eunsoeCoeNme:Nwoj>one_) }

Test it with:
vradn=rqie'/ul/ees/do' adoeur(.bidRlaeadn) vroj=nwadnMOjc(0 abedo.ybet1) cnoelgb.lsn(/1 osl.o(ojpuOe))/1 cnoelgb.lsn(/2 osl.o(ojpuOe))/1 cnoelgb.lsn(/3 osl.o(ojpuOe))/1

This is useful when you want to be able to create native objects without explicitly instantiating them with the operator in JavaScript, e.g.
vroj=adncetOjc( abdo.raebet) /ntaf /isedo: /abedo.bet) /vroj=nwadnOjc(

Let's register our c e t O j c method in a d n c : raebet do.c


#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh #nldmojc." icue"ybeth uignmsaev snaepc8 Hnl<au>CetOjc(osruet&ag){ adeVleraebetcntAgmnsrs HnlSoesoe adecpcp rtrcp.ls(ybet:eIsac(rs) eunsoeCoeMOjc:Nwntneag)

nodej .o g/api/all.h ml

33/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

} vintl(adeOjc>tre){ odIiAlHnl<betagt MOjc:Ii( ybet:nt) treStSrn:Nwybl"raebet) agt>e(tig:eSmo(cetOjc", FntoTmlt:NwCetOjc)>eFnto() ucinepae:e(raebetGtucin) } ND_OUEadnntl) OEMDL(do,IiAl

In m o j c . we now introduce the static method N w n t n e that takes care of instantiating the object (i ybeth eIsac it does the job of n w in JavaScript): e
#eieBIDN_OEETNIN dfnULIGND_XESO #fdfMOJC_ ineYBETH #eieMOJC_ dfnYBETH #nldnd.> icue<oeh casMOjculcnd:OjcWa lsybet:pbioe:betrp{ ulc pbi: saiodIi( ttcvint) sai8:adev:VleeIsac(os8:ruet&ag) ttcv:Hnl<8:au>Nwntnecntv:Agmnsrs rvt: piae MOjc( ybet) ~ybet) MOjc( sai8:essetv:Fnto>cntutr ttcv:Pritn<8:ucinosrco sai8:adev:Vlee(os8:ruet&ag) ttcv:Hnl<8:au>Nwcntv:Agmnsrs sai8:adev:Vlelsn(os8:ruet&ag) ttcv:Hnl<8:au>PuOecntv:Agmnsrs dulone_ obecutr } #ni edf

The implementation is similar to the above in m o j c . c: ybetc


#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh #nldmojc." icue"ybeth uignmsaev snaepc8 MOjc:MOjc(} ybet:ybet){ MOjc:~ybet){ ybet:MOjc(} Pritn<ucinybet:osrco essetFnto>MOjc:cntutr viybet:nt){ odMOjc:Ii(

nodej .o g/api/all.h ml

34/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

/rprosrcoepae /Peaecntutrtmlt LclFntoTmlt>tl=FntoTmlt:NwNw oa<ucinepaepucinepae:e(e) tl>eCasaeSrn:Nwybl"ybet) pStlsNm(tig:eSmo(MOjc") tl>ntneepae)>eItraFedon() pIsacTmlt(StnenlilCut1 /rttp /Pooye tl>rttpTmlt(StSrn:Nwybl"lsn", pPooyeepae)>e(tig:eSmo(puOe) FntoTmlt:NwPuOeGtucin) ucinepae:e(lsn)>eFnto() cntutr=Pritn<ucin:Nwtl>eFnto() osrcoessetFnto>:e(pGtucin) } Hnl<au>MOjc:NwcntAgmnsrs adeVleybet:e(osruet&ag){ HnlSoesoe adecpcp MOjc*oj=nwMOjc( ybetbeybet) oj>one_=ag[]>sneie(rs0NmeVle) bcutrrs0IUdfnd)?0:ag[]>ubrau( oj>rpag.hs) bWa(rsTi() rtrrsTi( eunag.hs) } Hnl<au>MOjc:NwntnecntAgmnsrs adeVleybet:eIsac(osruet&ag){ HnlSoesoe adecpcp cntusgerc=1 osnindag Hnl<au>ag[rcrs0 adeVlervag]={ag[]} LclOjc>isacosrcoNwntneag,ag) oa<betntne=cntutr>eIsac(rcrv rtrcp.ls(ntne eunsoeCoeisac) } Hnl<au>MOjc:PuOecntAgmnsrs adeVleybet:lsn(osruet&ag){ HnlSoesoe adecpcp MOjc*oj=OjcWa:Uwa<ybet(rsTi() ybetbbetrp:nrpMOjc>ag.hs) oj>one_+ bcutr=1 rtrcp.ls(ubr:e(bcutr) eunsoeCoeNme:Nwoj>one_) }

Test it with:
vradn=rqie'/ul/ees/do' adoeur(.bidRlaeadn) vroj=adncetOjc(0 abdo.raebet1) cnoelgb.lsn(/1 osl.o(ojpuOe))/1 cnoelgb.lsn(/2 osl.o(ojpuOe))/1 cnoelgb.lsn(/3 osl.o(ojpuOe))/1 vrojdo.raebet2) ab2=adncetOjc(0 cnoelgb2puOe))/2 osl.o(oj.lsn(/1 cnoelgb2puOe))/2 osl.o(oj.lsn(/2

nodej .o g/api/all.h ml

35/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelgb2puOe))/2 osl.o(oj.lsn(/3

In addition to wrapping and returning C++ objects, you can pass them around by unwrapping them with Nod n d : O j c W a : U w a helper function. In the following a d n c we introduce a function a d ) oe:betrp:nrp do.c d( can take on two M O j c objects: ybet
#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh #nldmojc." icue"ybeth uignmsaev snaepc8 Hnl<au>CetOjc(osruet&ag){ adeVleraebetcntAgmnsrs HnlSoesoe adecpcp rtrcp.ls(ybet:eIsac(rs) eunsoeCoeMOjc:Nwntneag) } Hnl<au>AdcntAgmnsrs adeVled(osruet&ag){ HnlSoesoe adecpcp MOjc*ojoe:betrp:nrpMOjc> ybetb1=nd:OjcWa:Uwa<ybet( ag[]>obet) rs0TOjc() MOjc*ojoe:betrp:nrpMOjc> ybetb2=nd:OjcWa:Uwa<ybet( ag[]>obet) rs1TOjc() dulub1>a(b2>a( obesm=ojVl)+ojVl) rtrcp.ls(ubr:e(u) eunsoeCoeNme:Nwsm) } vintl(adeOjc>tre){ odIiAlHnl<betagt MOjc:Ii( ybet:nt) treStSrn:Nwybl"raebet) agt>e(tig:eSmo(cetOjc", FntoTmlt:NwCetOjc)>eFnto() ucinepae:e(raebetGtucin) treStSrn:Nwybl"d", agt>e(tig:eSmo(ad) FntoTmlt:NwAdGtucin) ucinepae:e(d)>eFnto() } ND_OUEadnntl) OEMDL(do,IiAl

To make things interesting we introduce a public method in m o j c . so we can probe private values after ybeth unwrapping the object:
#eieBIDN_OEETNIN dfnULIGND_XESO #fdfMOJC_ ineYBETH #eieMOJC_ dfnYBETH

nodej .o g/api/all.h ml

36/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

#nldnd.> icue<oeh casMOjculcnd:OjcWa lsybet:pbioe:betrp{ ulc pbi: saiodIi( ttcvint) sai8:adev:VleeIsac(os8:ruet&ag) ttcv:Hnl<8:au>Nwntnecntv:Agmnsrs dula(oseunvl} obeVl)cnt{rtra_ rvt: piae MOjc( ybet) ~ybet) MOjc( sai8:essetv:Fnto>cntutr ttcv:Pritn<8:ucinosrco sai8:adev:Vlee(os8:ruet&ag) ttcv:Hnl<8:au>Nwcntv:Agmnsrs dula_ obevl } #ni edf

The implementation of m o j c . c is similar as before: ybetc


#eieBIDN_OEETNIN dfnULIGND_XESO #nldnd.> icue<oeh #nldmojc." icue"ybeth uignmsaev snaepc8 MOjc:MOjc(} ybet:ybet){ MOjc:~ybet){ ybet:MOjc(} Pritn<ucinybet:osrco essetFnto>MOjc:cntutr viybet:nt){ odMOjc:Ii( /rprosrcoepae /Peaecntutrtmlt LclFntoTmlt>tl=FntoTmlt:NwNw oa<ucinepaepucinepae:e(e) tl>eCasaeSrn:Nwybl"ybet) pStlsNm(tig:eSmo(MOjc") tl>ntneepae)>eItraFedon() pIsacTmlt(StnenlilCut1 cntutr=Pritn<ucin:Nwtl>eFnto() osrcoessetFnto>:e(pGtucin) } Hnl<au>MOjc:NwcntAgmnsrs adeVleybet:e(osruet&ag){ HnlSoesoe adecpcp MOjc*oj=nwMOjc( ybetbeybet) oj>a_=ag[]>sneie(rs0NmeVle) bvlrs0IUdfnd)?0:ag[]>ubrau( oj>rpag.hs) bWa(rsTi() rtrrsTi( eunag.hs) } Hnl<au>MOjc:NwntnecntAgmnsrs adeVleybet:eIsac(osruet&ag){

nodej .o g/api/all.h ml

37/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

HnlSoesoe adecpcp cntusgerc=1 osnindag Hnl<au>ag[rcrs0 adeVlervag]={ag[]} LclOjc>isacosrcoNwntneag,ag) oa<betntne=cntutr>eIsac(rcrv rtrcp.ls(ntne eunsoeCoeisac) }

Test it with:
vradn=rqie'/ul/ees/do' adoeur(.bidRlaeadn) vrojdo.raebet1) ab1=adncetOjc(0 vrojdo.raebet2) ab2=adncetOjc(0 vrrsldo.d(b1b2 aeut=adnadoj,oj) cnoelgrsl)/3 osl.o(eut/0

The p o e s object is a global object and can be accessed from anywhere. It is an instance of E e t m t e rcs vnEitr

:'

'

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 m not be scheduled. Example of listening for e i : xt
poeso(ei'ucin( rcs.n'xt,fnto){ poesnxTc(ucin( rcs.etikfnto){ osl.o(Tiilntrn) cnoelg'hswlou' } ) cnoelg'buoei.) osl.o(Aottxt' } )

:'

'

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. Example of listening for u c u h E c p i n: nagtxeto
poeso(ucuhEcpin,fntoer rcs.n'nagtxeto'ucin(r){

nodej .o g/api/all.h ml

38/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelg'agtecpinr) osl.o(Cuhxeto:'+er } ) stieu(ucin( eTmotfnto){ cnoelg'hswltlu.) osl.o(Tiilsilrn' }0) ,50 /netoalasnecpinuo'act /Itninlycueaxeto,btdntcthi. nnxsetuc) oeitnFn( cnoelg'hswlou.) osl.o(Tiilntrn'

Note that u c u h E c p i n is a very crude mechanism for exception handling. Using try / catch in your nagtxeto program will give you more control over your program's flow. Especially for server programs that are designed stay running forever, u c u h E c p i n can be a useful safety mechanism. nagtxeto

Emitted when the processes receives a signal. See sigaction(2) for a list of standard POSIX signal names such a SIGINT, SIGUSR1, etc. Example of listening for S G N : IIT
/trednrmsdnsedntei. /Satraigfotiowo'xt poessdnrsm( rcs.ti.eue) poeso(SGN'ucin( rcs.n'IIT,fnto){ cnoelg'oIITPesCnrlDtxt' osl.o(GtSGN.rsotooei.) } )

An easy way to send the S G N signal is with C n r l C in most terminal programs. IIT oto

.
A W i a l t e m to s d u . rtbeSra tot Example: the definition of c n o e l g osl.o
cnoelg=fntod osl.oucin(){ poessdu.rt(\' rcs.totwied+'n) }

p o e s s d r and p o e s s d u are unlike other streams in Node in that writes to them are usually rcs.ter rcs.tot

blocking. They are blocking in the case that they refer to regular files or TTY file descriptors. In the case they re to pipes, they are non-blocking like other streams.

.
A writable stream to stderr.

nodej .o g/api/all.h ml

39/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

p o e s s d r and p o e s s d u are unlike other streams in Node in that writes to them are usually rcs.ter rcs.tot

blocking. They are blocking in the case that they refer to regular files or TTY file descriptors. In the case they re to pipes, they are non-blocking like other streams.

.
A R a a l t e m for stdin. The stdin stream is paused by default, so one must call edbeSra
p o e s s d n r s m ( to read from it. rcs.ti.eue)

Example of opening standard input and listening for both events:


poessdnrsm( rcs.ti.eue) poessdnstnoig't8) rcs.ti.eEcdn(uf' poessdno(dt'ucin(hn){ rcs.ti.n'aa,fntocuk poessdu.rt(dt:'+cuk rcs.totwie'aahn) } ) poessdno(ed,fnto){ rcs.ti.n'n'ucin( poessdu.rt(ed) rcs.totwie'n' } )

An array containing the command line arguments. The first element will be 'node', the second element will be th name of the JavaScript file. The next elements will be any additional command line arguments.
/rnrcs.rv /pitpoesag poesag.oEc(ucin(a,idxra){ rcs.rvfrahfntovlne,ary cnoelgidx+'a) osl.o(ne:'+vl } )

This will generate:


$ndrcs.soetotrefu oepoes2jnw=heor 0oe :nd 1Uesmrwr/oepoes2j :/sr/j/oknd/rcs.s 2n :oe 3w=he :totre 4or :fu

.
Example:

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

nodej .o g/api/all.h ml

40/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

/s/oa/i/oe urlclbnnd

Changes the current working directory of the process or throws an exception if that fails.
cnoelg'trigdrcoyrcs.w() osl.o(Satnietr:'+poescd) ty{ r poescdr'tp) rcs.hi(/m' cnoelg'eietr:'+poescd) osl.o(Nwdrcoyrcs.w() } cth(r){ acer cnoelg'hi:'+er osl.o(cdrr) }

()

Returns the current working directory of the process.


cnoelg'urnietr:'+poescd) osl.o(Cretdrcoyrcs.w()

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

([

])

Ends the process with the specified c d . If omitted, exit uses the 'success' code 0. oe To exit with a 'failure' code:
poesei() rcs.xt1

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

()

Gets the group identity of the process. (See getgid(2).) This is the numerical group id, not the group name.
cnoelg'urni:'+poesgti() osl.o(Cretgdrcs.egd)

( )

nodej .o g/api/all.h ml

41/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

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.
cnoelg'urni:'+poesgti() osl.o(Cretgdrcs.egd) ty{ r poessti(0) rcs.egd51 cnoelg'ei:'+poesgti() osl.o(Nwgdrcs.egd) } cth(r){ acer cnoelg'aldtei:'+er osl.o(Fieostgdr) }

()

Gets the user identity of the process. (See getuid(2).) This is the numerical userid, not the username.
cnoelg'urni:'+poesgti() osl.o(Cretudrcs.eud)

( )

Sets the user identity of the process. (See setuid(2).) This accepts either a numerical ID or a username string. username is specified, this method blocks while resolving it to a numerical ID.
cnoelg'urni:'+poesgti() osl.o(Cretudrcs.eud) ty{ r poessti(0) rcs.eud51 cnoelg'ei:'+poesgti() osl.o(Nwudrcs.eud) } cth(r){ acer cnoelg'aldtei:'+er osl.o(Fieostudr) }

.
A compiled-in property that exposes N D _ E S O . OEVRIN
cnoelg'eso:'+poesvrin osl.o(Vrinrcs.eso)

.
A property exposing version strings of node and its dependencies.
cnoelgpoesvrin) osl.o(rcs.esos

Will output:

nodej .o g/api/all.h ml

42/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

{nd:'..2, oe041' v:'...6, 83182' ae:'..' rs174, e:'.' v44, oesl100is pns:'..efp'}

A compiled-in property that exposes N D _ R F X. OEPEI


cnoelg'rfxrcs.ntlPei) osl.o(Pei:'+poesisalrfx

,[

])

Send a signal to a process. p d is the process id and s g a is the string describing the signal to send. i inl 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 p o e s k l , it is really just a signal sender, like the rcs.il system call. The signal sent may do something other than kill the target process. Example of sending a signal to yourself:
poeso(SGU'ucin( rcs.n'IHP,fnto){ cnoelg'oIHPsga.) osl.o(GtSGUinl' } ) stieu(ucin( eTmotfnto){ cnoelg'xtn.) osl.o(Eiig' poesei() rcs.xt0 }0) ,10 poeskl(rcs.i,'IHP) rcs.ilpoespdSGU'

.
The PID of the process.
cnoelg'hspoesiircs.i) osl.o(Tircsspd'+poespd

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

nodej .o g/api/all.h ml

43/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

.
What processor architecture you're running on: ' r ', ' a 2 , or ' 6 '. am i3' x4
cnoelg'hspoesracietrs'+poesac) osl.o(Tircsorhtcueircs.rh

.
What platform you're running on. ' i u 2 , ' a w n , etc. lnx' dri'
cnoelg'hspafrs'+poespafr) osl.o(Tiltomircs.ltom

()

Returns an object describing the memory usage of the Node process measured in bytes.
vruieur(ui' atl=rqie'tl) cnoelgui.npc(rcs.eoysg() osl.o(tlisetpoesmmrUae))

This will generate:


{rs958, s:4360 haTtl861, epoa:1286 haUe:607 epsd542}

h a T t l and h a U e refer to V8's memory usage. epoa epsd

.
much more efficient.

On the next loop around the event loop call this callback. This is not a simple alias to s t i e u ( n ) eTmotf,0

poesnxTc(ucin( rcs.etikfnto){ cnoelg'etikclbc' osl.o(nxTcalak) } )

([

])

Sets or reads the process's file mode creation mask. Child processes inherit the mask from the parent process. Returns the old mask if m s argument is given, otherwise returns the current mask. ak
vrodakems64 alms,nwak=04 odak=poesuaknwak lmsrcs.ms(ems)

nodej .o g/api/all.h ml

44/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelg'hnemsrmlms.otig8 osl.o(Cagduakfo:'+odaktSrn()+ 'tems.otig8) o'+nwaktSrn()

()

Number of seconds Node has been running.

Saiiyokd tblt:5Lce

These functions are in the module ' t l . Use r q i e ' t l ) to access them. ui' eur(ui'

()

Returns a formatted string using the first argument as a p i t -like format. rnf The first argument is a string that contains zero or more placeholders. Each placeholder is replaced with the converted value from its corresponding argument. Supported placeholders are:
% - String. s % - Number (both integer and float). d % - JSON. j % - single percent sign (' ' This does not consume an argument. % % ).

If the placeholder does not have a corresponding argument, the placeholder is not replaced.
ui.omt's%'fo)/'o:s tlfra(%:s,'o'/fo%'

If there are more arguments than placeholders, the extra arguments are converted to strings with u i . n p c ( and these strings are concatenated, delimited by a space. tliset)
ui.omt's%'fo,'a'bz)/'o:aa' tlfra(%:s,'o'br,'a'/fobrbz

If the first argument is not a format string then u i . o m t ) returns a string that is the concatenation of al tlfra( its arguments separated by spaces. Each argument is converted to a string with u i . n p c ( . tliset)
ui.omt1,3/123 tlfra(,2)/''

A synchronous output function. Will block the process and output s r n immediately to s d r . tig ter

nodej .o g/api/all.h ml

45/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

rqie'tl)dbg'esgnsdr' eur(ui'.eu(msaeoter)

Output with timestamp on s d u . tot


rqie'tl)lg'ietmeesg.) eur(ui'.o(Tmsapdmsae'

,[

],[

],[

])

Return a string representation of o j c , which is useful for debugging. bet If s o H d e is t u , then the object's non-enumerable properties will be shown too. Defaults to f l e hwidn re as

If d p h is provided, it tells i s e t how many times to recurse while formatting the object. This is useful for et npc inspecting large complicated objects. The default is to only recurse twice. To make it recurse indefinitely, pass in n l for d p h. ul et If c l r is t u , the output will be styled with ANSI color codes. Defaults to f l e. oos re as Example of inspecting all properties of the u i object: tl
vruieur(ui' atl=rqie'tl) cnoelgui.npc(tlreul) osl.o(tlisetui,tu,nl)

. A

Returns t u if the given "object" is an A r y. f l e otherwise. re ra as


vruieur(ui' atl=rqie'tl) ui.sra(] tliAry[) /re /tu ui.sra(era) tliArynwAry /re /tu ui.sra(} tliAry{) /as /fle

. R

Returns t u if the given "object" is a R g x . f l e otherwise. re eEp as

nodej .o g/api/all.h ml

46/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

vruieur(ui' atl=rqie'tl) ui.seEp/oergx/ tliRgx(smeep) /re /tu ui.seEpnwRgx(aohrrgx') tliRgx(eeEp'nteeep) /re /tu ui.seEp{) tliRgx(} /as /fle

. D

Returns t u if the given "object" is a D t . f l e otherwise. re ae as


vruieur(ui' atl=rqie'tl) ui.saenwDt() tliDt(eae) /re /tu ui.saeDt() tliDt(ae) /aswtot'e'rtrsaSrn) /fle(ihunweuntig ui.sae{) tliDt(} /as /fle

. E

Returns t u if the given "object" is an E r r. f l e otherwise. re ro as


vruieur(ui' atl=rqie'tl) ui.sro(ero() tliErrnwErr) /re /tu ui.sro(eyero() tliErrnwTpErr) /re /tu ui.sro(aeErr,msaearocurd) tliErr{nm:'ro'esg:'nerrocre'} /as /fle

.
Experimental

,[

])

Read the data from r a a l S r a and send it to the w i a l S r a . When edbetem rtbetem on the w i a l S r a . c l b c gets an error as its only argument and is called when w i a l S r a rtbetem alak rtbetem closed or when an error occurs.

w i a l S r a . r t ( a a returns f l e r a a l S r a will be paused until the d a n event occurs rtbetemwiedt) as edbetem ri

nodej .o g/api/all.h ml

47/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Inherit the prototype methods from one constructor into another. The prototype of c n t u t r will be set to osrco new object created from s p r o s r c o . ueCntutr As an additional convenience, s p r o s r c o will be accessible through the c n t u t r s p r ueCntutr osrco.ue_ property.
vruieur(ui" atl=rqie"tl) vreeteur(eet" avns=rqie"vns) fntoytem){ ucinMSra( eet.vnEitrcl(hs vnsEetmte.alti) } ui.neisMSra,eet.vnEitr tlihrt(ytemvnsEetmte) MSra.rttp.rtucindt){ ytempooyewie=fnto(aa ti.mt"aa,dt) hsei(dt"aa } vrsraeytem) atem=nwMSra( cnoelgsrantnefeet.vnEitr/re osl.o(temisacovnsEetmte)/tu cnoelgMSra.ue_==eet.vnEitr/re osl.o(ytemspr=vnsEetmte)/tu sra.n"aa,fnto(aa temo(dt"ucindt){ cnoelg'eevddt:"aa+'' osl.o(Rcieaa'+dt") } ) sra.rt(Iok!)/RcieaaIok! temwie"twrs"/eevddt:"twrs"

E
SaiiyPrzn tblt:4AIFoe

Many objects in Node emit events: a n t S r e emits an event each time a peer connects to it, a e.evr
f . e d t e m emits an event when the file is opened. All objects which emit events are instances of sraSra e e t . v n E i t r You can access this module by doing: r q i e " v n s ) vnsEetmte . eur(eet"

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. Functions can then be attached to objects, to be executed when an event is emitted. These functions are called listeners.

.E

To access the EventEmitter class, r q i e ' v n s ) E e t m t e . eur(eet'.vnEitr

nodej .o g/api/all.h ml

48/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

When an E e t m t e instance experiences an error, the typical action is to emit an ' r o ' event. vnEitr err

events are treated as a special case in node. If there is no listener for it, then the default action is to print a stac trace and exit the program. All EventEmitters emit the event ' e L s e e ' when new listeners are added. nwitnr

. . (

L ,

( )

Adds a listener to the end of the listeners array for the specified event.
sre.n'oncin,fntosra){ evro(cneto'ucin(tem cnoelg'oenonce!) osl.o(smoecnetd' } )

Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which is removed.
sre.ne'oncin,fntosra){ evroc(cneto'ucin(tem cnoelg'hehvuissr' osl.o(A,waeorfrtue!) } )

Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.
vrclbcucinsra){ aalak=fnto(tem cnoelg'oenonce!) osl.o(smoecnetd' } sre.n'oncin,clbc) evro(cneto'alak /. /.. sre.eoeitnr'oncin,clbc) evrrmvLsee(cneto'alak

A L

([

])

Removes all listeners, or those of the specified event.

( )

nodej .o g/api/all.h ml

49/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

By default EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This functi allows that to be increased. Set to zero for unlimited.

Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners.
sre.n'oncin,fntosra){ evro(cneto'ucin(tem cnoelg'oenonce!) osl.o(smoecnetd' } ) cnoelgui.npc(evrlsees'oncin))/[[ucin osl.o(tlisetsre.itnr(cneto')/Fnto]]

,[

1],[

2],[...])

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

:'

'

e e tString The event name vn l s e e Function The event handler function itnr

This event is emitted any time someone adds a new listener.

B
Saiiytbe tblt:3Sal

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 B f e class. A B f e is similar to an array of integers but correspond ufr ufr to a raw memory allocation outside the V8 heap. A B f e cannot be resized. ufr The B f e class is a global, making it very rare that one would need to ever r q i e ' u f r ). ufr eur(bfe' Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings.
' s i ' - for 7 bit ASCII data only. This encoding method is very fast, and will strip the high bit if set. aci

Note that this encoding converts a null character ( ' 0 or ' u 0 0 ) into 0 2 (character code of a \' \00' x0 space). If you want to convert a null character into 0 0 , you should use ' t 8 . x0 uf'

' t 8 - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF uf'

nodej .o g/api/all.h ml

50/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

8.
' c 2 - 2-bytes, little endian encoded Unicode characters. It can encode only BMP(Basic Multilingual us'

Plane, U+0000 - U+FFFF). ' a e 4 - Base64 string encoding. bs6'

' i a y - A way of encoding raw binary data into strings by using only the first 8 bits of each character bnr'

This encoding method is deprecated and should be avoided in favor of B f e objects where possible. Th ufr encoding will be removed in future versions of Node. ' e ' - Encode each byte as two hexidecimal characters. hx

:B

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

s z Number ie

Allocates a new buffer of s z octets. ie

a r yArray ra

Allocates a new buffer using an a r y of octets. ra

,[

])

s rString - string to encode. t e c d n String - encoding to use, Optional. noig

Allocates a new buffer containing the given s r. e c d n defaults to ' t 8 . t noig uf'

,[

],[

],[

])

s r n String - data to be written to buffer tig o f e Number, Optional, Default: 0 fst l n t Number, Optional egh e c d n String, Optional, Default: 'utf8' noig

Writes s r n to the buffer at o f e using the given encoding. o f e defaults to 0, e c d n defaults to tig fst fst noig
' t 8 . l n t is the number of bytes to write. Returns number of octets written. If b f e did not contain uf' egh ufr

enough space to fit the entire string, it will write a partial amount of the string. l n t defaults to egh
b f e . e g h o f e . The method will not write partial characters. ufrlntfst

bf=nwBfe(5) ueufr26 ln=bfwie'u0d+\0bu0e,0 eu.rt(\0bu0c=\0b')

nodej .o g/api/all.h ml

51/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelgln+"btsu.otig't8,0e) osl.o(eye:"+bftSrn(uf',ln)

The number of characters written (which may be different than the number of bytes written) is set in B f e . c a s r t e and will be overwritten the next time b f w i e ) is called. ufr_hrWitn u.rt(

. S

([

],[

],[

])

e c d n String, Optional, Default: 'utf8' noig s a tNumber, Optional, Default: 0 tr e dNumber, Optional n

Decodes and returns a string from buffer data encoded with e c d n (defaults to ' t 8 ) beginning at noig uf'
s a t (defaults to 0 and ending at e d (defaults to b f e . e g h tr ) n u f r l n t ).

See b f e . r t ( example, above. ufrwie)

Get and set the octet at i d x. The values refer to individual bytes, so the legal range is between 0 0 and ne x0
0 F hex or 0 and 2 5 xF 5.

Example: copy an ASCII string into a buffer, one byte at a time:


sr="oej" tnd.s bf=nwBfe(t.egh ueufrsrlnt) fr(ai<srlnt+){ ovri=0t.eghi+ bfit.hroeti u[]=srcaCdA() } cnoelgbf osl.o(u) /oej /nd.s

M
o jObject b

:B

. B

Return: Boolean Tests if o j is a B f e . b ufr

M
s r n String tig

:B

,[

])

e c d n String, Optional, Default: 'utf8' noig

Return: Number

nodej .o g/api/all.h ml

52/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Gives the actual byte length of a string. e c d n defaults to ' t 8 . This is not the same as noig uf'
S r n . r t t p . e g h since that returns the number of characters in a string. tigpooyelnt

Example:
sr='u0d+\0bu0e t\0bu0c=\0b' cnoelgsr+"t.egh+"caatr,"+ osl.o(t:"+srlnthrces Bfe.yeeghsruf'ye" ufrbtLnt(t,'t8)+"bts) /:9caatr,1ye /+= hrces2bts

.
Number The size of the buffer in bytes. Note that this is not necessarily the size of the contents. l n t refers to the egh amount of memory allocated for the buffer object. It does not change when the contents of the buffer are changed.
bf=nwBfe(24 ueufr13) cnoelgbflnt) osl.o(u.egh bfwie"oesrn"aci,0 u.rt(smtig,"si") cnoelgbflnt) osl.o(u.egh /24 /13 /24 /13

,[

],[

],[

])

t r e B f e Buffer object - Buffer to copy into agtufr t r e S a tNumber, Optional, Default: 0 agttr s u c S a tNumber, Optional, Default: 0 oretr s u c E dNumber, Optional, Default: 0 oren

Does copy between buffers. The source and target regions can be overlapped. t r e S a t and s u c S a t agttr oretr default to 0. s u c E d defaults to b f e . e g h. oren ufrlnt

Example: build two Buffers, then copy b f from byte 16 through byte 19 into b f , starting at the 8th byte in u1 u2
bf . u2

bfeufr2) u1=nwBfe(6 bfeufr2) u2=nwBfe(6 fr(a6i+ ovri=0i<2+){ bf[]=i+9/7iSI u1i7/9sACIa

nodej .o g/api/all.h ml

53/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

bf[]=3/SI u2i3/ACI! } bf.oybf,860 u1cp(u2,1,2) cnoelgbf.otig'si',2) osl.o(u2tSrn(aci,05) /!!!!rt!!!!!! /!!!!qs!!!!!!!

([

],[

])

s a tNumber, Optional, Default: 0 tr e dNumber, Optional, Default: 0 n

Returns a new buffer which references the same memory as the old, but offset and cropped by the s a t tr (defaults to 0) and e d (defaults to b f e . e g h) indexes. n ufrlnt Modif ing the ne buffer slice ill modif memor in the original buffer! Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer.
vrbfeufr2) au1=nwBfe(6 fr(a6i+ ovri=0i<2+){ bf[]=i+9/7iSI u1i7/9sACIa } vrbfu1sie0) au2=bf.lc(,3 cnoelgbf.otig'si',bf.egh) osl.o(u2tSrn(aci,0u2lnt) bf[]=3 u103 cnoelgbf.otig'si',bf.egh) osl.o(u2tSrn(aci,0u2lnt) /b /ac /b /!c

UI 8(

,[

])

o f e Number fst n A s r Boolean, Optional, Default: false oset

Return: Number Reads an unsigned 8 bit integer from the buffer at the specified offset. Set n A s r to true to skip validation of o f e . This means that o f e may be beyond the end of the oset fst fst buffer. Defaults to f l e as . Example:
vrbf=nwBfe() aueufr4

nodej .o g/api/all.h ml

54/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

bf0x u[]=03 bf1x u[]=04 bf2x3 u[]=02 bf3x2 u[]=04 fr(i=0i<bflnti+){ oiiu.eghi+ cnoelgbfraUn8i) osl.o(u.edIt(i) } /x /03 /x /04 /x3 /02 /x2 /04

. .

UI 16LE( UI 16BE(

,[ ,[

A A

]) ])

o f e Number fst n A s r Boolean, Optional, Default: false oset

Return: Number Reads an unsigned 16 bit integer from the buffer at the specified offset with specified endian format. Set n A s r to true to skip validation of o f e . This means that o f e may be beyond the end of the oset fst fst buffer. Defaults to f l e as . Example:
vrbf=nwBfe() aueufr4 bf0x u[]=03 bf1x u[]=04 bf2x3 u[]=02 bf3x2 u[]=04 cnoelgbfraUn1B() osl.o(u.edIt6E0) cnoelgbfraUn1L() osl.o(u.edIt6E0) cnoelgbfraUn1B() osl.o(u.edIt6E1) cnoelgbfraUn1L() osl.o(u.edIt6E1) cnoelgbfraUn1B() osl.o(u.edIt6E2) cnoelgbfraUn1L() osl.o(u.edIt6E2) /x34 /000 /x43 /000 /x43 /002 /x34 /020 /x32 /024 /x23 /042

nodej .o g/api/all.h ml

55/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

. .

UI 32LE( UI 32BE(

,[ ,[

A A

]) ])

o f e Number fst n A s r Boolean, Optional, Default: false oset

Return: Number Reads an unsigned 32 bit integer from the buffer at the specified offset with specified endian format. Set n A s r to true to skip validation of o f e . This means that o f e may be beyond the end of the oset fst fst buffer. Defaults to f l e as . Example:
vrbf=nwBfe() aueufr4 bf0x u[]=03 bf1x u[]=04 bf2x3 u[]=02 bf3x2 u[]=04 cnoelgbfraUn3B() osl.o(u.edIt2E0) cnoelgbfraUn3L() osl.o(u.edIt2E0) /x3432 /00024 /x2343 /04200

I 8(

,[

])

o f e Number fst n A s r Boolean, Optional, Default: false oset

Return: Number Reads a signed 8 bit integer from the buffer at the specified offset. Set n A s r to true to skip validation of o f e . This means that o f e may be beyond the end of the oset fst fst buffer. Defaults to f l e as . Works as b f e . e d I t , except buffer contents are treated as two's complement signed values. ufrraUn8

. .

I 16LE( I 16BE(

,[ ,[

A A

]) ])

o f e Number fst n A s r Boolean, Optional, Default: false oset

Return: Number

nodej .o g/api/all.h ml

56/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Reads a signed 16 bit integer from the buffer at the specified offset with specified endian format. Set n A s r to true to skip validation of o f e . This means that o f e may be beyond the end of the oset fst fst buffer. Defaults to f l e as . Works as b f e . e d I t 6 , except buffer contents are treated as two's complement signed values. ufrraUn1*

. .

I 32LE( I 32BE(

,[ ,[

A A

]) ])

o f e Number fst n A s r Boolean, Optional, Default: false oset

Return: Number Reads a signed 32 bit integer from the buffer at the specified offset with specified endian format. Set n A s r to true to skip validation of o f e . This means that o f e may be beyond the end of the oset fst fst buffer. Defaults to f l e as . Works as b f e . e d I t 2 , except buffer contents are treated as two's complement signed values. ufrraUn3*

. .

F F

LE( BE(

,[ ,[

A A

]) ])

o f e Number fst n A s r Boolean, Optional, Default: false oset

Return: Number Reads a 32 bit float from the buffer at the specified offset with specified endian format. Set n A s r to true to skip validation of o f e . This means that o f e may be beyond the end of the oset fst fst buffer. Defaults to f l e as . Example:
vrbf=nwBfe() aueufr4 bf0x0 u[]=00 bf1x0 u[]=00 bf2x0 u[]=08 bf3xf u[]=03 cnoelgbfraFotE0) osl.o(u.edlaL() /x1 /00

nodej .o g/api/all.h ml

57/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

. .

D D

LE( BE(

,[ ,[

A A

]) ])

o f e Number fst n A s r Boolean, Optional, Default: false oset

Return: Number Reads a 64 bit double from the buffer at the specified offset with specified endian format. Set n A s r to true to skip validation of o f e . This means that o f e may be beyond the end of the oset fst fst buffer. Defaults to f l e as . Example:
vrbf=nwBfe() aueufr8 bf0x5 u[]=05 bf1x5 u[]=05 bf2x5 u[]=05 bf3x5 u[]=05 bf4x5 u[]=05 bf5x5 u[]=05 bf6x5 u[]=0d bf7xf u[]=03 cnoelgbfraDulL() osl.o(u.edobeE0) /.33333333 /033333333

UI 8(

,[

])

v l eNumber au o f e Number fst n A s r Boolean, Optional, Default: false oset

Writes v l e to the buffer at the specified offset. Note, v l e must be a valid unsigned 8 bit integer. au au

Set n A s r to true to skip validation of v l e and o f e . This means that v l e may be too large for th oset au fst au This should not be used unless you are certain of correctness. Defaults to f l e. as Example:
vrbf=nwBfe() aueufr4 bfwieIt(x,0 u.rtUn803) bfwieIt(x,1 u.rtUn804) bfwieIt(x3) u.rtUn802,2 bfwieIt(x2) u.rtUn804,3

specific function and o f e may be beyond the end of the buffer leading to the values being silently dropped fst

nodej .o g/api/all.h ml

58/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelgbf osl.o(u) /Bfe3034> /<ufr0422

. .

UI 16LE( UI 16BE(

, ,

,[ ,[

A A

]) ])

v l eNumber au o f e Number fst n A s r Boolean, Optional, Default: false oset

Writes v l e to the buffer at the specified offset with specified endian format. Note, v l e must be a valid au au unsigned 16 bit integer.

Set n A s r to true to skip validation of v l e and o f e . This means that v l e may be too large for th oset au fst au This should not be used unless you are certain of correctness. Defaults to f l e. as Example:
vrbf=nwBfe() aueufr4 bfwieIt6E0da,0 u.rtUn1B(xed) bfwieIt6E0be,2 u.rtUn1B(xef) cnoelgbf osl.o(u) bfwieIt6E0da,0 u.rtUn1L(xed) bfwieIt6E0be,2 u.rtUn1L(xef) cnoelgbf osl.o(u) /Bfeeaee> /<ufrddbf /Bfeddfb> /<ufraeee

specific function and o f e may be beyond the end of the buffer leading to the values being silently dropped fst

. .

UI 32LE( UI 32BE(

, ,

,[ ,[

A A

]) ])

v l eNumber au o f e Number fst n A s r Boolean, Optional, Default: false oset

Writes v l e to the buffer at the specified offset with specified endian format. Note, v l e must be a valid au au unsigned 32 bit integer.

Set n A s r to true to skip validation of v l e and o f e . This means that v l e may be too large for th oset au fst au

specific function and o f e may be beyond the end of the buffer leading to the values being silently dropped fst

nodej .o g/api/all.h ml

59/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

This should not be used unless you are certain of correctness. Defaults to f l e. as Example:
vrbf=nwBfe() aueufr4 bfwieIt2E0fefc,0 u.rtUn3B(xedae) cnoelgbf osl.o(u) bfwieIt2E0fefc,0 u.rtUn3L(xedae) cnoelgbf osl.o(u) /Bfeeeac> /<ufrfdfe /Bfeefdf> /<ufrcaee

I 8(

,[

])

v l eNumber au o f e Number fst n A s r Boolean, Optional, Default: false oset

Writes v l e to the buffer at the specified offset. Note, v l e must be a valid signed 8 bit integer. au au

Set n A s r to true to skip validation of v l e and o f e . This means that v l e may be too large for th oset au fst au This should not be used unless you are certain of correctness. Defaults to f l e. as Works as b f e . r t U n 8, except value is written out as a two's complement signed integer into b f e ufrwieIt ufr

specific function and o f e may be beyond the end of the buffer leading to the values being silently dropped fst

. .

I 16LE( I 16BE(

, ,

,[ ,[

A A

]) ])

v l eNumber au o f e Number fst n A s r Boolean, Optional, Default: false oset

Writes v l e to the buffer at the specified offset with specified endian format. Note, v l e must be a valid au au signed 16 bit integer.

Set n A s r to true to skip validation of v l e and o f e . This means that v l e may be too large for th oset au fst au This should not be used unless you are certain of correctness. Defaults to f l e. as Works as b f e . r t U n 1 *, except value is written out as a two's complement signed integer into ufrwieIt6

specific function and o f e may be beyond the end of the buffer leading to the values being silently dropped fst

nodej .o g/api/all.h ml

60/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

. .

I 32LE( I 32BE(

, ,

,[ ,[

A A

]) ])

v l eNumber au o f e Number fst n A s r Boolean, Optional, Default: false oset

Writes v l e to the buffer at the specified offset with specified endian format. Note, v l e must be a valid au au signed 32 bit integer.

Set n A s r to true to skip validation of v l e and o f e . This means that v l e may be too large for th oset au fst au This should not be used unless you are certain of correctness. Defaults to f l e. as Works as b f e . r t U n 3 *, except value is written out as a two's complement signed integer into ufrwieIt2

specific function and o f e may be beyond the end of the buffer leading to the values being silently dropped fst

. .

F F

LE( BE(

, ,

,[ ,[

A A

]) ])

v l eNumber au o f e Number fst n A s r Boolean, Optional, Default: false oset

Writes v l e to the buffer at the specified offset with specified endian format. Note, v l e must be a valid 32 au au bit float.

Set n A s r to true to skip validation of v l e and o f e . This means that v l e may be too large for th oset au fst au This should not be used unless you are certain of correctness. Defaults to f l e. as Example:
vrbf=nwBfe() aueufr4 bfwielaB(xaeae) u.rtFotE0cfbb,0 cnoelgbf osl.o(u) bfwielaL(xaeae) u.rtFotE0cfbb,0 cnoelgbf osl.o(u) /Bfef4eb> /<ufr4afb /Bfebfa4> /<ufrbe4f

specific function and o f e may be beyond the end of the buffer leading to the values being silently dropped fst

. .
nodej .o g/api/all.h ml

D D

LE( BE(

, ,

,[ ,[

A A

]) ])
61/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

v l eNumber au o f e Number fst n A s r Boolean, Optional, Default: false oset

Writes v l e to the buffer at the specified offset with specified endian format. Note, v l e must be a valid 64 au au bit double.

Set n A s r to true to skip validation of v l e and o f e . This means that v l e may be too large for th oset au fst au This should not be used unless you are certain of correctness. Defaults to f l e. as Example:
vrbf=nwBfe() aueufr8 bfwieobeE0dabecfbb,0 u.rtDulB(xedefaeae) cnoelgbf osl.o(u) bfwieobeE0dabecfbb,0 u.rtDulL(xedefaeae) cnoelgbf osl.o(u) /Bfe3e5bdffd> /<ufr4bd7d957 /Bfe759d7db4> /<ufrdffdb5e3

specific function and o f e may be beyond the end of the buffer leading to the values being silently dropped fst

,[

],[

])

vle au o f e Number, Optional fst e dNumber, Optional n

Fills the buffer with the specified value. If the o f e (defaults to 0) and e d (defaults to b f e . e g h fst n ufrlnt are not given it will fill the entire buffer.
vrb=nwBfe(0 aeufr5) bfl(h) .il""

.INSPECT_MAX_BYTES
Number, Default: 50 How many bytes will be returned when b f e . n p c ( is called. This can be overridden by user modules. ufriset)

Note that this is a property on the buffer module returned by r q i e ' u f r ), not on the Buffer global, o eur(bfe' buffer instance.

C
nodej .o g/api/all.h ml

:S

B
62/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

This class is primarily for internal use. JavaScript programs should use Buffer instead of using SlowBuffer.

In order to avoid the overhead of allocating many C++ Buffer objects for small blocks of memory in the lifetime of a server, Node allocates memory in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it will be backed by a parent SlowBuffer object. If it is larger than this, then Node will allocate a SlowBuffer slab for it directly.

S
Saiiyntbe tblt:2Usal

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 of Eetmte . vnEitr You can load up the Stream base class by doing r q i e ' t e m ). eur(sra'

A R a a l t e m has the following methods, members, and events. edbeSra

:'

'

fntodt){} ucin(aa

The ' a a event emits either a B f e (by default) or a string if s t n o i g ) was used. dt' ufr eEcdn( Note that the data ill be lost if there is no listener when a R a a l t e m emits a ' a a event. edbeSra dt'

:'

'

fnto){} ucin(

Emitted when the stream has received an EOF (FIN in TCP terminology). Indicates that no more ' a a dt' will happen. If the stream is also writable, it may be possible to continue writing.

:'

'

fntoecpin ucin(xeto){}

Emitted if there was an error receiving data.

:'

'

nodej .o g/api/all.h ml

63/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

fnto){} ucin(

Emitted when the underlying file descriptor has been closed. Not all streams will emit this. (For example, an incoming HTTP request will not emit ' l s '.) coe

.
A boolean that is t u by default, but turns f l e after an ' r o ' occurred, the stream came to an re as err or d s r y ) was called. eto(

Makes the data event emit a string instead of a B f e . e c d n can be ' t 8 , ' s i ', or ' a e 4 ufr noig uf' aci bs6'

()

Pauses the incoming ' a a events. dt'

()

Resumes the incoming ' a a events after a p u e ). dt' as(

()

Closes the underlying file descriptor. Stream will not emit any more events.

()

After the write queue is drained, close the file descriptor.

,[

])

This is a S r a . r t t p method available on all S r a s. tempooye tem Connects this read stream to d s i a i n WriteStream. Incoming data on this stream gets written to etnto
d s i a i n The destination and source streams are kept in sync by pausing and resuming as necessary. etnto .

This function returns the d s i a i n stream. etnto Emulating the Unix c t command: a
poessdnrsm( rcs.ti.eue) poessdnpp(rcs.tot rcs.ti.iepoessdu)

nodej .o g/api/all.h ml

64/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

By default e d ) is called on the destination when the source stream emits e d, so that d s i a i n n( n etnto longer writable. Pass { e d a s as o t o s to keep the destination stream open. n:fle} pin This keeps p o e s s d u open so that "Goodbye" can be written at the end. rcs.tot
poessdnrsm( rcs.ti.eue) poessdnpp(rcs.totn:fle} rcs.ti.iepoessdu,{edas) poessdno(ed,fnto( rcs.ti.n"n"ucin){ poessdu.rt(Goben) rcs.totwie"ody\" } )

A W i a l t e m has the following methods, members, and events. rtbeSra

:'

'

fnto){} ucin(

After a w i e ) method returned f l e, this event is emitted to indicate that it is safe to write again. rt( as

:'

'

fntoecpin ucin(xeto){}

Emitted on error with the exception e c p i n. xeto

:'

'

fnto){} ucin(

Emitted when the underlying file descriptor has been closed.

:'

'

fntosc ucin(r){}

Emitted when the stream is passed to a readable stream's pipe method.

nodej .o g/api/all.h ml

65/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

A boolean that is t u by default, but turns f l e after an ' r o ' occurred or e d ) / d s r y ) re as err n( eto( called.

,[

],[ ])

Writes s r n with the given e c d n to the stream. Returns t u if the string has been flushed to the kern tig noig re buffer. Returns f l e to indicate that the kernel buffer is full, and the data will be sent out in the future. The as
' r i ' event will indicate when the kernel buffer is empty again. The e c d n defaults to ' t 8 . dan noig uf'

If the optional f parameter is specified, it is interpreted as an integral file descriptor to be sent over the stream d

This is only supported for UNIX streams, and is silently ignored otherwise. When writing a file descriptor in thi manner, closing the descriptor before the stream drains risks sending an invalid (closed) FD.

Same as the above except with a raw buffer.

()

Terminates the stream with EOF or FIN. This call will allow queued write data to be sent before closing the stream.

Sends s r n with the given e c d n and terminates the stream with EOF or FIN. This is useful to reduce t tig noig number of packets sent.

Same as above but with a b f e . ufr

()

Closes the underlying file descriptor. Stream will not emit any more events. Any queued write data will not be sent.

()

After the write queue is drained, close the file descriptor. d s r y o n ) can still destroy straight away, as lon etoSo( as there is no data left in the queue for writes.

nodej .o g/api/all.h ml

66/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

C
Saiiytbe tblt:3Sal

Use r q i e ' r p o ) to access this module. eur(cyt'

The crypto module requires OpenSSL to be available on the underlying platform. It offers a way of encapsulatin 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.

Creates a credentials object, with the optional details being a dictionary with keys:
k y: a string holding the PEM encoded private key e c r : a string holding the PEM encoded certificate et c : either a string or list of strings of PEM encoded CA certificates to trust. a c p e s a string describing the ciphers to use or exclude. Consult ihr:

http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format. If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generat hash digests.
a g r t m is dependent on the available algorithms supported by the version of OpenSSL on the platform. loih a g r t m will display the available digest algorithms. loihs

Examples are ' h 1 , ' d ', ' h 2 6 , ' h 5 2 , etc. On recent releases, o e s l l s e s g i e sa' m5 sa5' sa1' pnsitmsaedgs

Example: this program that takes the sha1 sum of a file


vrflnmrcs.rv2 aieae=poesag[] vrcyteur(cyt' arpo=rqie'rpo) vrfeur(f' as=rqie's) vrsaurpocetHs(sa' ahsm=cyt.raeah'h1) vrs=f.edtemflnm) asRaSra(ieae so(dt'ucind .n'aa,fnto(){ sau.paed hsmudt() } ) so(ed,fnto( .n'n'ucin){ vrd=sau.iet'e' ahsmdgs(hx)

nodej .o g/api/all.h ml

67/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelgd+'ieae osl.o('+flnm) } )

:H

The class for creating hash digests of data. Returned by c y t . r a e a h. rpocetHs

,[

])

Updates the hash content with the given d t , the encoding of which is given in i p t e c d n and can be aa nu_noig
' t 8 , ' s i ' or ' i a y . Defaults to ' i a y . This can be called many times with new data as it is uf' aci bnr' bnr'

streamed.

([

])

Calculates the digest of all of the passed data to be hashed. The e c d n can be ' e ', ' i a y or noig hx bnr'
' a e 4 . Defaults to ' i a y . bs6' bnr'

Note: h s object can not be used after d g s ( method been called. ah iet)

Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
a g r t m is dependent on the available algorithms supported by OpenSSL - see createHash above. k y loih e

hmac key to be used.

:H

Class for creating cryptographic hmac content. Returned by c y t . r a e m c. rpocetHa

Update the hmac content with the given d t . This can be called many times with new data as it is streamed. aa

([

])

Calculates the digest of all of the passed data to the hmac. The e c d n can be ' e ', ' i a y or noig hx bnr'
' a e 4 . Defaults to ' i a y . bs6' bnr'

nodej .o g/api/all.h ml

68/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Note: h a object can not be used after d g s ( method been called. mc iet)

Creates and returns a cipher object, with the given algorithm and password.

a g r t m is dependent on OpenSSL, examples are ' e 1 2 , etc. On recent releases, o e s l l s i h loih as9' pnsitcpe ' i a y encoded string (See the Buffer section for more information). bnr'

a g r t m will display the available cipher algorithms. p s w r is used to derive key and IV, which must be loihs asod

, )

Creates and returns a cipher object, with the given algorithm, key and iv.
a g r t m is the same as the c e t C p e ( . k y is a raw key used in algorithm. i is an Initialization loih raeihr) e v

vector. k y and i must be ' i a y encoded string (See the Buffer section for more information). e v bnr'

:C

Class for encrypting data. Returned by c y t . r a e i h r and c y t . r a e i h r v. rpocetCpe rpocetCpei

,[

],[

])

Updates the cipher with d t , the encoding of which is given in i p t e c d n and can be ' t 8 , aa nu_noig uf'
' s i ' or ' i a y . Defaults to ' i a y . aci bnr' bnr'

The o t u _ n o i g specifies the output format of the enciphered data, and can be ' i a y , ' a e 4 uptecdn bnr' bs6'
' e ' Defaults to ' i a y . hx . bnr'

Returns the enciphered contents, and can be called many times with new data as it is streamed.

([

])

Returns any remaining enciphered contents, with o t u _ n o i g being one of: ' i a y , ' a e 4 uptecdn bnr' bs6'
' e ' Defaults to ' i a y . hx . bnr'

Note: c p e object can not be used after f n l ) method been called. ihr ia(

Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the createCipher( above.

nodej .o g/api/all.h ml

69/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

, )

Creates and returns a decipher object, with the given algorithm, key and iv. This is the mirror of the createCipheriv() above.

:D

Class for decrypting data. Returned by c y t . r a e e i h r and c y t . r a e e i h r v. rpocetDcpe rpocetDcpei

,[

],[

])

Updates the decipher with d t , which is encoded in ' i a y , ' a e 4 or ' e '. Defaults to ' i a y aa bnr' bs6' hx bnr' The o t u _ e o i g specifies in what format to return the deciphered plaintext: ' i a y , ' s i ' uptdcdn bnr' aci
' t 8 . Defaults to ' i a y . uf' bnr'

([

])

Returns any remaining plaintext which is deciphered, with o t u _ n o i g being one of: ' i a y , uptecdn bnr'
' s i ' or ' t 8 . Defaults to ' i a y . aci uf' bnr'

Note: d c p e object can not be used after f n l ) method been called. eihr ia(

Creates and returns a signing object, with the given algorithm. On recent OpenSSL releases, o e s l l s pnsit
p b i e l o i h s will display the available signing algorithms. Examples are ' S H 2 6 . ulckyagrtm RASA5'

:S

Class for generating signatures. Returned by c y t . r a e i n. rpocetSg

Updates the signer object with data. This can be called many times with new data as it is streamed.

,[

])

Calculates the signature on all the updated data passed through the signer. p i a e k y is a string containin rvt_e the PEM encoded private key for signing.

nodej .o g/api/all.h ml

70/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Returns the signature in o t u _ o m t which can be ' i a y , ' e ' or ' a e 4 . Defaults to ' i a y uptfra bnr' hx bs6' bnr' Note: s g e object can not be used after s g ( method been called. inr in)

Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above

:V

Class for verifying signatures. Returned by c y t . r a e e i y. rpocetVrf

Updates the verifier object with data. This can be called many times with new data as it is streamed.

,[

])

Verifies the signed data by using the o j c and s g a u e. o j c is a string containing a PEM encoded bet intr bet object, which can be one of RSA public key, DSA public key, or X.509 certificate. s g a u e is the previously intr calculated signature for the data, in the s g a u e f r a which can be ' i a y , ' e ' or ' a e 4 intr_omt bnr' hx bs6' Defaults to ' i a y . bnr' Returns true or false depending on the validity of the signature for the data and public key. Note: v r f e object can not be used after v r f ( method been called. eiir eiy)

Creates a Diffie-Hellman key exchange object and generates a prime of the given bit length. The generator used is 2.

,[

])

Creates a Diffie-Hellman key exchange object using the supplied prime. The generator used is 2. Encoding can be ' i a y , ' e ', or ' a e 4 . Defaults to ' i a y . bnr' hx bs6' bnr'

:D

The class for creating Diffie-Hellman key exchanges. Returned by c y t . r a e i f e e l a . rpocetDfiHlmn

nodej .o g/api/all.h ml

71/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

H
'iay . bnr'

([

])

Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party. Encoding can be ' i a y , ' e ', or ' a e 4 . Defaults t bnr' hx bs6'

H _

],[

_ ])

Computes the shared secret using o h r p b i _ e as the other party's public key and returns the compute te_ulcky
o t u _ n o i g Encodings can be ' i a y , ' e ' or ' a e 4 . The input encoding defaults to uptecdn . bnr' hx , bs6' ' i a y . If no output encoding is given, the input encoding is used as output encoding. bnr'

shared secret. Supplied key is interpreted using specified i p t e c d n , and secret is encoded using specifi nu_noig

([

])

Returns the Diffie-Hellman prime in the specified encoding, which can be ' i a y , ' e ', or ' a e 4 bnr' hx bs6' Defaults to ' i a y . bnr'

([

])

Returns the Diffie-Hellman prime in the specified encoding, which can be ' i a y , ' e ', or ' a e 4 bnr' hx bs6' Defaults to ' i a y . bnr'

([

])

Returns the Diffie-Hellman public key in the specified encoding, which can be ' i a y , ' e ', or ' a e 4 bnr' hx bs6' Defaults to ' i a y . bnr'

([

])

Returns the Diffie-Hellman private key in the specified encoding, which can be ' i a y , ' e ', or ' a e 4 bnr' hx bs6 Defaults to ' i a y . bnr'

H
'iay . bnr'

,[

])

Sets the Diffie-Hellman public key. Key encoding can be ' i a y , ' e ', or ' a e 4 . Defaults to bnr' hx bs6'

H
'iay . bnr'

,[

])

Sets the Diffie-Hellman private key. Key encoding can be ' i a y , ' e ', or ' a e 4 . Defaults to bnr' hx bs6'

nodej .o g/api/all.h ml

72/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

2(

Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive a key of given length from the given password, salt and iterations. The callback gets two arguments ( r , d r v d e ). ereieKy

,[

])

Generates cryptographically strong pseudo-random data. Usage:


/sn /ayc cyt.admye(5,fnto(xu){ rpornoBts26ucine,bf ie)trwe f(xhox cnoelg'ae%yefrnoaas,bflnt,bf osl.o(Hvdbtsoadmdt:%'u.eghu) } ) /yc /sn ty{ r vrbf=cyt.admye(5) aurpornoBts26 cnoelg'ae%yefrnoaas,bflnt,bf osl.o(Hvdbtsoadmdt:%'u.eghu) }cth(x ace){ /adeerr /hnlro }

TLS(SSL)
Saiiytbe tblt:3Sal

Use r q i e ' l ' to access this module. eur(ts) The t s module uses OpenSSL to provide Transport Layer Security and/or Secure Socket Layer: encrypted l stream communication.

TLS/SSL is a public/private key infrastructure. Each client and each server must have a private key. A private k is created like this
oeslgnsotraskypm12 pnserauyne.e04

All severs and some clients need to have a certificate. Certificates are public keys signed by a Certificate Authori or self-signed. The first step to getting a certificate is to create a "Certificate Signing Request" (CSR) file. This is done with:
oeslrqekyraskypmuyns.e pnsenweyne.eotrascrpm

To create a self-signed certificate with the CSR, do this:


oeslx0rqnrascrpmineyne.eotrascr.e pns59eiyns.esgkyraskypmuynetpm

nodej .o g/api/all.h ml

73/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

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 t s / i t r s k y / a e i e etfxue/esMkfl the Node source code)

The TLS protocol lets the client renegotiate certain aspects of the TLS session. Unfortunately, session renegotiation requires a disproportional amount of server-side resources, which makes it a potential vector for denial-of-service attacks. To mitigate this, renegotiations are limited to three times every 10 minutes. An error is emitted on the CleartextStream instance when the threshold is exceeded. The limits are configurable:
t s C I N _ E E _ I I : renegotiation limit, default is 3. l.LETRNGLMT t s C I N _ E E _ I D W renegotiation window in seconds, default is l.LETRNGWNO : 0mnts 1iue.

Don't change the defaults unless you know what you are doing.

To test your server, connect to it with o e s l s c i n c n e t a d e s p r and tap R C > (that's the pns_letoncdrs:ot <R letter R followed by a carriage return) a few times.

NPN

SNI

NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS handshake extensions allowing you: NPN - to use one TLS server for multiple protocols (HTTP, SPDY) SNI - to use one TLS server for multiple hostnames with different SSL certificates.

,[

])

Creates a new tls.Server. The c n e t o L s e e argument is automatically set as a listener for the oncinitnr secureConnection event. The o t o s object has these possibilities: pin
k y A string or B f e containing the private key of the server in PEM format. (Required) e: ufr p s p r s : A string of passphrase for the private key. ashae c r : A string or B f e containing the certificate key of the server in PEM format. (Required) et ufr

c : An array of strings or B f e s of trusted certificates. If this is omitted several well known "root" CAs a ufr

will be used, like VeriSign. These are used to authorize connections. c p e s A string describing the ciphers to use or exclude. Consult ihr :

http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT for details on the format. r q e t e t If t u the server will request a certificate from clients that connect and attempt to verify eusCr : re that certificate. Default: f l e. as
r j c U a t o i e : If t u the server will reject any connection which is not authorized with the list eetnuhrzd re

supplied CAs. This option only has an effect if r q e t e t is t u . Default: f l e. eusCr re as

nodej .o g/api/all.h ml

74/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

N N r t c l : An array or B f e of possible NPN protocols. (Protocols should be ordered by their PPooos ufr

priority). be passed to it: s r e n m . And S I a l a k should return SecureContext instance. (You can use evrae NClbc
c y t . r a e r d n i l ( . ) c n e t to get proper SecureContext). If S I a l a k wasn't rpocetCeetas...otx NClbc

S I a l a k A function that will be called if client supports SNI TLS extension. Only one argument will NClbc :

provided - default callback with high-level API will be used (see below). s s i n d o t x : A string containing a opaque identifier for session resumption. If r q e t e t esoICnet eusCr

t u , the default is MD5 hash value generated from command-line. Otherwise, the default is not provide re

Here is a simple example echo server:


vrts=rqie'l' aleur(ts) vrfeur(f' as=rqie's) vrotos={ apin kysraFlSn(sree.e', e:f.edieyc'evrkypm) cr:f.edieyc'evrcr.e', etsraFlSn(sreetpm) /hsieesrnyisnhletcriiaeatetcto. /Tisncsayolfuigtecinetfctuhniain rqetetre eusCr:tu, /hsieesrnyihletuehefsgeetfct. /Tisncsayolftecinssteslindcriiae c:[f.edieyc'letcr.e' asraFlSn(cinetpm)] } vrsrel.raeevrotosucincerettem aevr=tscetSre(pin,fnto(latxSra){ cnoelg'evrcnetd, osl.o(sreonce' cerettematoieatoie':'nuhrzd) latxSra.uhrzd?'uhrzduatoie' cerettemwie"ecm!n) latxSra.rt(wloe\" cerettemstnoig't8) latxSra.eEcdn(uf' cerettempp(latxSra) latxSra.iecerettem } ) sre.itn80,fnto( evrlse(00ucin){ cnoelg'evrbud) osl.o(sreon' } )

You can test this server by connecting to it with o e s l s c i n : pns_let


oeslscincnet1700180 pns_letonc2...:00

,[

],[

],[

])

Creates a new client connection to the given p r and h s . (If h s defaults to l c l o t.) o t o s ot ot ot oahs pin should be an object which specifies
k y A string or B f e containing the private key of the client in PEM format. e: ufr p s p r s : A string of passphrase for the private key. ashae c r : A string or B f e containing the certificate key of the client in PEM format. et ufr

c : An array of strings or B f e s of trusted certificates. If this is omitted several well known "root" CAs a ufr

nodej .o g/api/all.h ml

75/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

will be used, like VeriSign. These are used to authorize connections. N N r t c l : An array of string or B f e containing supported NPN protocols. B f e should have PPooos ufr ufr following format: 0 0 h l o x 5 o l , where first byte is next protocol name's length. (Passing array x5el00wrd should usually be much simpler: [ h l o , ' o l ' .) 'el'wrd]
s r e n m : Servername for SNI (Server Name Indication) TLS extension. evrae

s c e : Establish secure connection on a given socket rather than creating a new socket. If this option is okt

specified, h s and p r are ignored. This is intended FOR INTERNAL USE ONLY. As with all ot ot undocumented APIs in Node, they should not be used. The s c r C n e t i t n r parameter will be added as a listener for the 'secureConnect' event. eueoncLsee
t s c n e t ) returns a CleartextStream object. l.onc(

Here is an example of a client of echo server as described previously:


vrts=rqie'l' aleur(ts) vrfeur(f' as=rqie's) vrotos={ apin /hsreesrnyisnhletcriiaeatetcto /Teeaencsayolfuigtecinetfctuhniain kysraFlSn(cine.e', e:f.edieyc'letkypm) cr:f.edieyc'letcr.e', etsraFlSn(cinetpm) /hsieesrnyihevruehefsgeetfct /Tisncsayolftesressteslindcriiae c:[f.edieyc'evrcr.e' asraFlSn(sreetpm)] } vrcerettem=tscnet80,otosucin){ alatxSral.onc(00pin,fnto( cnoelg'letcnetd, osl.o(cinonce' cerettematoieatoie':'nuhrzd) latxSra.uhrzd?'uhrzduatoie' poessdnpp(latxSra) rcs.ti.iecerettem poessdnrsm( rcs.ti.eue) } ) cerettemstnoig't8) latxSra.eEcdn(uf' cerettemo(dt'ucindt){ latxSra.n'aa,fnto(aa cnoelgdt) osl.o(aa } ) cerettemo(ed,fnto( latxSra.n'n'ucin){ sre.ls( evrcoe) } )

([ ])

],[ S

],[

],

Creates a new secure pair object with two streams, one of which reads/writes encrypted data, and one reads/writes cleartext data. Generally the encrypted one is piped to/from an incoming encrypted data stream, and the cleartext one is used as a replacement for the initial encrypted stream.
c e e t a s A credentials object from crypto.createCredentials( ... ) rdnil : i S r e : A boolean indicating whether this tls connection should be opened as a server or a client. sevr

nodej .o g/api/all.h ml

76/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

r q e t e t A boolean indicating whether a server should request a certificate from a connecting clien eusCr :

Only applies to server connections. r j c U a t o i e : A boolean indicating whether a server should automatically reject clients with eetnuhrzd invalid certificates. Only applies to servers with r q e t e t enabled. eusCr
t s c e t S c r P i ( returns a SecurePair object with cleartext and e c y t d stream properties. l.raeeuear) nrpe

:S

Returned by tls.createSecurePair.

:'

'

The event is emitted from the SecurePair once the pair has successfully established a secure connection.

Similarly to the checking for the server 'secureConnection' event, pair.cleartext.authorized should be checked to confirm whether the certificate used properly authorized.

.S

This class is a subclass of n t S r e and has the same methods on it. Instead of accepting just raw TCP e.evr connections, this accepts encrypted connections using TLS or SSL.

:'

'

fntocerettem} ucin(latxSra){

This event is emitted after a new connection has been successfully handshaked. The argument is a instance of CleartextStream. It has all the common stream methods and events.
c e r e t t e m a t o i e is a boolean value which indicates if the client has verified by one of the latxSra.uhrzd

supplied certificate authorities for the server. If c e r e t t e m a t o i e is false, then latxSra.uhrzd


c e r e t t e m a t o i a i n r o is set to describe how authorization failed. Implied but worth latxSra.uhrztoErr

mentioning: depending on the settings of the TLS server, you unauthorized connections may be accepted. c e r e t t e m n n r t c l is a string containing selected NPN protocol. c e r e t t e m s r e n m latxSra.pPooo latxSra.evrae is a string containing servername requested with SNI.

:'

'

fntoecpin ucin(xeto){}

When a client connection emits an 'error' event before secure connection is established - it will be forwarded he

,[

],[

])

Begin accepting connections on the specified p r and h s . If the h s is omitted, the server will accept ot ot ot

nodej .o g/api/all.h ml

77/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

connections directed to any IPv4 address ( I A D _ N ). NDRAY This function is asynchronous. The last parameter c l b c will be called when the server has been bound. alak See n t S r e for more information. e.evr

()

Stops the server from accepting new connections. This function is asynchronous, the server is finally closed whe the server emits a ' l s ' event. coe

()

Returns the bound address and port of the server as reported by the operating system. See net.Server.address() for more information.

Add secure context that will be used if client request's SNI hostname is matching passed h s n m (wildcards otae can be used). c e e t a s can contain k y, c r and c . rdnil e et a

Set this property to reject connections when the server's connection count gets high.

.
The number of concurrent connections on the server.

.C

This is a stream on top of the Encr pted stream that makes it possible to read/write an encrypted data as a cleartext data. This instance implements a duplex Stream interfaces. It has all the common stream methods and events. A ClearTextStream is the c e r member of a SecurePair object. la

:'

'

This event is emitted after a new connection has been successfully handshaked. The listener will be called no matter if the server's certificate was authorized or not. It is up to the user to test c e r e t t e m a t o i e latxSra.uhrz to see if the server certificate was signed by one of the specified CAs. If c e r e t t e m a t o i e = latxSra.uhrzd==

f l e then the error can be found in c e r e t t e m a t o i a i n r o . Also if NPN was used - you ca as latxSra.uhrztoErr

nodej .o g/api/all.h ml

78/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

check c e r e t t e m n n r t c l for negotiated protocol. latxSra.pPooo

A boolean that is t u if the peer certificate was signed by one of the specified CAs, otherwise f l e re as

The reason why the peer's certificate has not been verified. This property becomes available only when cerettematoie=as . latxSra.uhrzd==fle

()

Returns an object representing the peer's certificate. The returned object has some properties corresponding to the field of the certificate. Example:
{sbet ujc: :'K, {CU' TAkakLd, S:'cnct' :'hsJns, LRyoe' :'oej' Ond.s, UTsLetfct' O:'etTSCriiae, Nlclot, C:'oahs'} ise: sur :'K, {CU' TAkakLd, S:'cnct' :'hsJns, LRyoe' :'oej' Ond.s, UTsLetfct' O:'etTSCriiae, Nlclot, C:'oahs'} vldfo:'o10:2209GT, ai_rmNv195:220M' vldt:'o60:2209GT, ai_oNv95:222M' fnepit2:AC:DE:9C:37:59:A0:A7:85:C8:F igrrn:'A7:2D:5F:C5:23:97:25:13:2E:AD'}

If the peer does not provide a certificate, it returns n l or an empty object. ul

()

Returns the bound address and port of the underlying socket as reported by the operating system. Returns an object with two properties, e.g. { a d e s : 1 2 1 8 5 . " p r " 6 0 3 "drs""9.6.71,"ot:25}

The string representation of the remote IP address. For example, ' 4 1 5 1 7 1 0 or 7.2.2.0'

nodej .o g/api/all.h ml

79/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

'0146:05:8 . 20:80a0:6'

The numeric representation of the remote port. For example, 4 3. 4

S
Saiiytbe tblt:3Sal

File I/O is provided by simple wrappers around standard POSIX functions. To use this module do r q i e ' s ) All the methods have asynchronous and synchronous forms. eur(f' . 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 n l or u d f n d. ul neie When using the synchronous form any exceptions are immediately thrown. You can use try/catch to handle exceptions or allow them to bubble up. Here is an example of the asynchronous version:
vrfeur(f' as=rqie's) f.nik'tphlo,fntoer suln(/m/el'ucin(r){ ierhor f(r)trwer cnoelg'ucsflydltd/m/el' osl.o(scesuleeetphlo) } )

Here is the synchronous version:


vrfeur(f' as=rqie's) f.nikyc'tphlo) sulnSn(/m/el' cnoelg'ucsflydltd/m/el' osl.o(scesuleeetphlo)

With the asynchronous methods there is no guaranteed ordering. So the following is prone to error:
f.eae'tphlo,'tpwrd,fntoer srnm(/m/el'/m/ol'ucin(r){ ierhor f(r)trwer cnoelg'eaeopee) osl.o(rnmdcmlt' } ) f.tt'tpwrd,fntoertt){ ssa(/m/ol'ucin(r,sas ierhor f(r)trwer cnoelg'tt:'+JO.tigf(tt) osl.o(sasSNsrniysas) } )

nodej .o g/api/all.h ml

80/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

It could be that f . t t is executed before f . e a e. The correct way to do this is to chain the callbacks. ssa srnm
f.eae'tphlo,'tpwrd,fntoer srnm(/m/el'/m/ol'ucin(r){ ierhor f(r)trwer f.tt'tpwrd,fntoertt){ ssa(/m/ol'ucin(r,sas ierhor f(r)trwer cnoelg'tt:'+JO.tigf(tt) osl.o(sasSNsrniysas) } ) } )

In busy processes, the programmer is strongl encouraged to use the asynchronous versions of these calls. The synchronous versions will block the entire process until they complete--halting all connections. Relative path to filename can be used, remember however that this path will be relative to p o e s c d ) rcs.w(

1,

2,[

])

Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.

1,

2)

Synchronous rename(2).

( ,

,[

])

Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback

( ,

Synchronous ftruncate(2).

,[

])

Asynchronous chown(2). No arguments other than a possible exception are given to the completion callback.

Synchronous chown(2).

( ,

,[

])

Asynchronous fchown(2). No arguments other than a possible exception are given to the completion callback.

( ,

Synchronous fchown(2).

nodej .o g/api/all.h ml

81/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

,[

])

Asynchronous lchown(2). No arguments other than a possible exception are given to the completion callback.

Synchronous lchown(2).

,[

])

Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.

Synchronous chmod(2).

( ,

,[

])

Asynchronous fchmod(2). No arguments other than a possible exception are given to the completion callback.

( ,

Synchronous fchmod(2).

,[

])

Asynchronous lchmod(2). No arguments other than a possible exception are given to the completion callback.

Synchronous lchmod(2).

,[

])

Asynchronous stat(2). The callback gets two arguments ( r , s a s where s a s is a fs.Stats object. ertt) tt fs.Stats section below for more information.

,[

])

Asynchronous lstat(2). The callback gets two arguments ( r , s a s where s a s is a f . t t object. ertt) tt sSas that it refers to.

l t t ) is identical to s a ( , except that if p t is a symbolic link, then the link itself is stat-ed, not the file sa( tt) ah

( ,[

])

Asynchronous fstat(2). The callback gets two arguments ( r , s a s where s a s is a f . t t object. ertt) tt sSas

nodej .o g/api/all.h ml

82/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

f t t ) is identical to s a ( , except that the file to be stat-ed is specified by the file descriptor f . sa( tt) d

Synchronous stat(2). Returns an instance of f . t t . sSas

Synchronous lstat(2). Returns an instance of f . t t . sSas

( )

Synchronous fstat(2). Returns an instance of f . t t . sSas

,[

])

Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.

Synchronous link(2).

.
other platforms).

,[

],[

])

Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback. t p argument can be either ' i ' or ' i e (default is ' i e ). It is only used on Windows (ignored on ye dr fl' fl'

,[

])

Synchronous symlink(2).

,[

])

Asynchronous readlink(2). The callback gets two arguments ( r , l n S r n ). eriktig

Synchronous readlink(2). Returns the symbolic link's string value.

,[

])

Asynchronous realpath(2). The callback gets two arguments ( r , r s l e P t ). May use p o e s c d ereovdah rcs.w resolve relative paths.

nodej .o g/api/all.h ml

83/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Synchronous realpath(2). Returns the resolved path.

,[

])

Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.

Synchronous unlink(2).

,[

])

Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.

Synchronous rmdir(2).

,[

],[

])

Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback. m d defaults to 0 7 . oe 77

,[

])

Synchronous mkdir(2).

,[

])

Asynchronous readdir(3). Reads the contents of a directory. The callback gets two arguments ( r , f l s erie) where f l s is an array of the names of the files in the directory excluding ' ' and ' . . ie . .'

Synchronous readdir(3). Returns an array of filenames excluding ' ' and ' . . . .'

( ,[

])

Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.

( )

Synchronous close(2).

nodej .o g/api/all.h ml

84/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

,[

],[

])

Asynchronous file open. See open(2). f a s can be: lg


' ' - Open file for reading. An exception occurs if the file does not exist. r ' + - Open file for reading and writing. An exception occurs if the file does not exist. r' ' ' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists). w ' ' - Open file for appending. The file is created if it does not exist. a ' + - Open file for reading and appending. The file is created if it does not exist. a' m d defaults to 0 6 . The callback gets two arguments ( r , f ) oe 66 erd .

' + - Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). w'

,[

])

Synchronous open(2).

. .

( S

, ( ,

, ,

,[ )

])

Change file timestamps of the file referenced by the supplied path.

. .

( , S ( ,

, ,

,[ )

])

Change the file timestamps of a file referenced by the supplied file descriptor.

( ,[

])

Asynchronous fsync(2). No arguments other than a possible exception are given to the completion callback.

( )

Synchronous fsync(2).

( ,

,[

])

Write b f e to the file specified by f . ufr d


o f e and l n t determine the part of the buffer to be written. fst egh p s t o refers to the offset from the beginning of the file where this data should be written. If p s t o oiin oiin n l , the data will be written at the current position. See pwrite(2). ul

The callback will be given three arguments ( r , w i t n u f r where w i t n specifies how many errte,bfe) rte were written from b f e . ufr

nodej .o g/api/all.h ml

85/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Note that it is unsafe to use f . r t multiple times on the same file without waiting for the callback. For this swie scenario, f . r a e r t S r a is strongly recommended. scetWietem

( ,

Synchronous version of buffer-based f . r t ( . Returns the number of bytes written. swie)

.
written.

( ,

,[

])

Synchronous version of string-based f . r t ( . e c d n defaults to ' t 8 . Returns the number of swie) noig uf'

( ,

,[

])

Read data from the file specified by f . d


b f e is the buffer that the data will be written to. ufr o f e is offset within the buffer where writing will start. fst l n t is an integer specifying the number of bytes to read. egh p s t o is an integer specifying where to begin reading from in the file. If p s t o is n l , data will be oiin oiin ul

read from the current file position. The callback is given the three arguments, ( r , b t s e d u f r . eryeRa,bfe)

( ,

Synchronous version of buffer-based f . e d. Returns the number of b t s e d. sra yeRa

( ,

Synchronous version of string-based f . e d. Returns the number of b t s e d. sra yeRa

F (

,[

],[

])

Asynchronously reads the entire contents of a file. Example:


f.edie'ecpsw'ucin(r,dt){ sraFl(/t/asd,fntoeraa ierhor f(r)trwer cnoelgdt) osl.o(aa } )

The callback is passed two arguments ( r , d t ), where d t is the contents of the file. eraa aa If no encoding is specified, then the raw buffer is returned.

nodej .o g/api/all.h ml

86/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

F S

,[

])

Synchronous version of f . e d i e. Returns the contents of the f l n m . sraFl ieae If e c d n is specified then this function returns a string. Otherwise it returns a buffer. noig

F (

,[

],[

])

Asynchronously writes data to a file, replacing the file if it already exists. d t can be a string or a buffer. The aa
e c d n argument is ignored if d t is a buffer. It defaults to ' t 8 . noig aa uf'

Example:
f.rtFl(msaett,'eloe,fntoer swieie'esg.x'HloNd'ucin(r){ ierhor f(r)trwer cnoelg't'ae!) osl.o(I\ssvd' } )

F S

,[

])

The synchronous version of f . r t F l . swieie

F (

,[

],

SaiiyntbeUef.acnta,ivial. tblt:2Usal.sswthisedfaalbe

Watch for changes on f l n m . The callback l s e e will be called each time the file is accessed. ieae itnr The second argument is optional. The o t o s if provided should be an object containing two members a pin boolean, p r i t n , and i t r a . p r i t n indicates whether the process should continue to run as esset nevl esset Linux systems with inotify, i t r a is ignored.) The default is { p r i t n : t u , i t r a : 0 } nevl essetrenevl The l s e e gets two arguments the current stat object and the previous stat object: itnr
f.acFl(msaetx'ucin(urrv swthie'esg.et,fntocr,pe){ cnoelg'hurntmsurmie osl.o(tecretmiei:'+cr.tm) cnoelg'hrvosmiewsrvmie osl.o(tepeiutma:'+pe.tm) } )

long as files are being watched. i t r a indicates how often the target should be polled, in milliseconds. (On nevl

These stat objects are instances of f . t t. sSa If you want to be notified when the file was modified, not just accessed you need to compare c r . t m urmie
pe.tm . rvmie

.
nodej .o g/api/all.h ml

F (

)
87/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

SaiiyntbeUef.acnta,ivial. tblt:2Usal.sswthisedfaalbe

Stop watching for changes on f l n m . ieae

,[

],

SaiiyntbeNtaalbeolltom. tblt:2Usal.ovialnalpafrs

Watch for changes on f l n m , where f l n m is either a file or a directory. The returned object is a ieae ieae fs.FSWatcher. The second argument is optional. The o t o s if provided should be an object containing a boolean member pin default is { p r i t n : t u . essetre} The listener callback gets two arguments ( v n , f l n m ). e e t is either 'rename' or 'change', and eetieae vn
f l n m is the name of the file which triggered the event. ieae

p r i t n , which indicates whether the process should continue to run as long as files are being watched. Th esset

C
The f . a c API is not 100% consistent across platforms, and is unavailable in some situations. swth

A
This feature depends on the underlying operating system providing a way to be notified of filesystem changes. On Linux systems, this uses i o i y ntf. On BSD systems (including OS X), this uses k u u . qee On SunOS systems (including Solaris and SmartOS), this uses e e t p r s vnot. On Windows systems, this feature depends on R a D r c o y h n e W edietrCags. If the underlying functionality is not available for some reason, then f . a c will not be able to function. swth can still use f . a c F l , which uses stat polling, but it is slower and less reliable. swthie

Providing f l n m argument in the callback is not supported on every platform (currently it's only supported ieae on Linux and Windows). Even on supported platforms f l n m is not always guaranteed to be provided. ieae Therefore, don't assume that f l n m argument is always provided in the callback, and have some fallback ieae logic if it is null.
f.ac(smdr,fntoeetieae swth'oei'ucin(vn,flnm){ cnoelg'vnsvn) osl.o(eeti:'+eet iflnm){ f(ieae cnoelg'ieaepoie:'+flnm) osl.o(flnmrvddieae }es le{ cnoelg'ieaentpoie' osl.o(flnmorvdd)

nodej .o g/api/all.h ml

88/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

} } )

C
this type.

: .S

Objects returned from f . t t ), f . s a ( and f . s a ( and their synchronous counterparts are of ssa( sltt) sftt)

sasiFl( tt.sie) sasiDrcoy) tt.sietr( sasiBokeie) tt.slcDvc( sasiCaatreie) tt.shrceDvc( s a s i S m o i L n ( (only valid with f . s a ( ) tt.syblcik) sltt) sasiFF( tt.sIO) sasiSce( tt.sokt)

For a regular file u i . n p c ( t t ) would return a string very similar to this: tlisetsas
{dv14 e:21, io8699 n:4046, md:318 oe38, nik, ln:1 ud5 i:8, gd0, i:10 re:0 dv, sz:57 ie2, bkie06 lsz:49, bok:8 lcs, aieo,1c012:41M, tm:Mn0Ot2132:1GT mieo,1c012:41M, tm:Mn0Ot2132:1GT cieo,1c012:41M tm:Mn0Ot2132:1GT}

Please note that a i e, m i e and c i e are instances of Date object and to compare the values of these tm tm tm

objects you should use appropriate methods. For most general uses getTime() will return the number of milliseconds elapsed since 1 Januar 1970 00:00:00 UTC and this integer should be sufficient for any compariso however there additional methods which can be used for displaying fuzzy information. More details can be foun in the MDN JavaScript Reference page.

,[

])

Returns a new ReadStream object (See R a a l t e m). edbeSra


o t o s is an object with the following defaults: pin

{fasr, lg:'' ecdn:nl, noigul f:nl, dul md:06, oe66 bfeSz:604 ufrie4*12

nodej .o g/api/all.h ml

89/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

o t o s can include s a t and e d values to read a range of bytes from the file instead of the entire file. pin tr n s a t and e d are inclusive and start at 0. tr n

An example to read the last 10 bytes of a file which is 100 bytes long:
f.raeedtem'apett,{tr:9,ed9) scetRaSra(sml.x'sat0n:9}

: .R

R a S r a is a Readable Stream. edtem

:'

'

f Integer file descriptor used by the ReadStream. d

Emitted when the ReadStream's file is opened.

,[

])

Returns a new WriteStream object (See W i a l t e m). rtbeSra


o t o s is an object with the following defaults: pin

{fasw, lg:'' ecdn:nl, noigul md:06 oe66}

o t o s may also include a s a t option to allow writing data at some position past the beginning of the file pin tr

Modifying a file rather than replacing it may require a f a s mode of r rather than the default mode lg +

.W

W i e t e m is a Writable Stream. rtSra

:'

'

f Integer file descriptor used by the ReadStream. d

Emitted when the WriteStream's file is opened.

nodej .o g/api/all.h ml

90/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The number of bytes written so far. Does not include data that is still queued for writing.

: .FSW

Objects returned from f . a c ( are of this type. swth)

()

Stop watching for changes on the given f . S a c e . sFWthr

:'

'

e e tString The type of fs change vn f l n m String The filename that changed (if relevant/available) ieae

Emitted when something changes in a watched directory or file. See more details in fs.watch.

:'

'

e r rError object ro

Emitted when an error occurs.

P
Saiiytbe tblt:3Sal

This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformations. The file system is not consulted to check whether paths are valid.

p t . x s s and p t . x s s y c are the exceptions, and should logically be found in the fs module as the aheit aheitSn

do access the file system. Use r q i e ' a h ) to use this module. The following methods are provided: eur(pt'

( )

Normalize a string path, taking care of ' . and ' ' parts. .' . When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On windows backslashes are used. Example:

nodej .o g/api/all.h ml

91/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

pt.omlz(/o/a/bzad/ux.' ahnraie'fobr/a/sfqu/.) /eun /rtrs 'fobrbzad' /o/a/a/sf

.
Example:

([

1],[

2],[...])

Join all arguments together and normalize the resulting path. Non-string arguments are ignored.

pt.on'fo,'a'bzad'qu'.' ahji(/o'br,'a/sf,'ux,'.) /eun /rtrs 'fobrbzad' /o/a/a/sf pt.on'o'}br) ahji(fo,{,'a' /eun /rtrs 'o/a' fobr

([

...], )

Resolves t to an absolute path. o

If t isn't already absolute f o arguments are prepended in right to left order, until an absolute path is foun o rm If after using all f o paths still no absolute path is found, the current working directory is used as well. The rm

resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory Non-string arguments are ignored. Another way to think of it is as a sequence of c commands in a shell. d
pt.eov(fobr,'tpfl/,'.,'/.sbie) ahrsle'o/a'/m/ie'.'a./ufl'

Is similar to:
co/a dfobr ctpfl/ d/m/ie c. d. c/.sbie da./ufl pd w

The difference is that the different paths don't need to exist and may also be files. Examples:
pt.eov(/o/a'.bz) ahrsle'fobr,'/a' /eun /rtrs 'fobrbz /o/a/a'

nodej .o g/api/all.h ml

92/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

pt.eov(/o/a'/m/ie' ahrsle'fobr,'tpfl/) /eun /rtrs 'tpfl' /m/ie pt.eov(wwot,'ttcflspg'./i/mg.i' ahrsle'wro'sai_ie/n/,'.gfiaegf) /fcretyihm/yefnd,ieun /iurnln/oemsl/oetrtrs 'hm/yefnd/wro/ttcflsgfiaegf /oemsl/oewwotsai_ie/i/mg.i'

, )

Solve the relative path from f o to t . rm o At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of p t . e o v , which means we see that: ahrsle
pt.eov(rmahrltv(rmo)=ahrslet) ahrslefo,pt.eaiefo,t)=pt.eov(o

Examples:
pt.eaie':\rne\ts\aa,':\rne\ip\bb) ahrltv(C\oada\et\a'C\oada\ml\b' /eun /rtrs '.\.\ml\b' .\.\ip\bb pt.eaie'dt/rne/etaa,'dt/rne/mlbb) ahrltv(/aaoadats/a'/aaoadaip/b' /eun /rtrs '../mlbb ./.ip/b'

.
Example:

( )

Return the directory name of a path. Similar to the Unix d r a e command. inm

pt.inm(/o/a/a/sfqu' ahdrae'fobrbzad/ux) /eun /rtrs 'fobrbzad' /o/a/a/sf

.
Example:

( ,[

])

Return the last portion of a path. Similar to the Unix b s n m command. aeae

pt.aeae'fobrbzad/uxhm' ahbsnm(/o/a/a/sfqu.tl) /eun /rtrs

nodej .o g/api/all.h ml

93/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

'uxhm' qu.tl pt.aeae'fobrbzad/uxhm'.tl) ahbsnm(/o/a/a/sfqu.tl,'hm' /eun /rtrs 'ux qu'

( )

Return the extension of the path, from the last '.' to end of string in the last portion of the path. If there is no '.' the last portion of the path or the first character of it is '.', then it returns an empty string. Examples:
pt.xnm(idxhm' ahetae'ne.tl) /eun /rtrs 'hm' .tl pt.xnm(idx' ahetae'ne.) /eun /rtrs '' . pt.xnm(idx) ahetae'ne' /eun /rtrs ' '

( ,[

])

Test whether or not the given path exists by checking with the file system. Then call the c l b c argument alak with either true or false. Example:
pt.xss'ecpsw'ucin(xss aheit(/t/asd,fntoeit){ ui.eu(xss?"tsteenasd" tldbgeiti'hr":"opsw!) } )

( )

Synchronous version of p t . x s s. aheit

Saiiytbe tblt:3Sal

The n t module provides you with an asynchronous network wrapper. It contains methods for creating both e servers and clients (called streams). You can include this module with r q i e ' e ' eur(nt)

.
nodej .o g/api/all.h ml

([

],[

])
94/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Creates a new TCP server. The c n e t o L s e e argument is automatically set as a listener for the oncinitnr 'connection' event.
o t o s is an object with the following defaults: pin

{alwafpnas loHlOe:fle }

If a l w a f p n is t u , then the socket won't automatically send FIN packet when the other end of the loHlOe re socket sends a FIN packet. The socket becomes non-readable, but still writable. You should call the e d ) n( method explicitly. See 'end' event for more information. Here is an example of a echo server which listens for connections on port 8124:
vrnt=rqie'e' aeeur(nt) vrsree.raeevrfnto(){/'oncinitnr aevr=ntcetSre(ucinc/cneto'lsee cnoelg'evrcnetd) osl.o(sreonce' co(ed,fnto( .n'n'ucin){ cnoelg'evrdsonce' osl.o(sreicnetd) } ) cwie'el\\' .rt(hlorn) cpp() .iec } ) sre.itn82,fnto(/lseigitnr evrlse(14ucin){/'itnn'lsee cnoelg'evrbud) osl.o(sreon' } )

Test this by using t l e : ent


tleoahs14 entlclot82

To listen on the socket / m / c o s c the third line from the last would just be changed to tpeh.ok
sre.itn'tpeh.ok,fnto(/lseigitnr evrlse(/m/cosc'ucin){/'itnn'lsee

Use n to connect to a UNIX domain socket server: c


nU/m/cosc ctpeh.ok

. . C

( (

...) ...)

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 these methods change the type of connection:

nodej .o g/api/all.h ml

95/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

ntcnetpr,[ot,[oncLsee] e.onc(oths]cnetitnr) ntcetCneto(oths]cnetitnr) e.raeoncinpr,[ot,[oncLsee]

Creates a TCP connection to p r on h s . If h s is omitted, ' o a h s ' will be assumed. ot ot ot lclot


ntcnetpt,[oncLsee] e.onc(ahcnetitnr) ntcetCneto(ahcnetitnr) e.raeoncinpt,[oncLsee]

Creates unix socket connection to p t . ah The c n e t i t n r parameter will be added as an listener for the 'connect' event. oncLsee Here is an example of a client of echo server as described previously:
vrnt=rqie'e' aeeur(nt) vrcine.onc(14ucin){/'onc'lsee alet=ntcnet82,fnto(/cnetitnr cnoelg'letcnetd) osl.o(cinonce' cin.rt(wrd\\' letwie'ol!rn) } ) cin.n'aa,fnto(aa leto(dt'ucindt){ cnoelgdt.otig) osl.o(aatSrn() cin.n( leted) } ) cin.n'n'ucin){ leto(ed,fnto( cnoelg'letdsonce' osl.o(cinicnetd) } )

To connect on the socket / m / c o s c the second line would just be changed to tpeh.ok
vrcine.onc(/m/cosc'ucin){/'onc'lsee alet=ntcnet'tpeh.ok,fnto(/cnetitnr

.S

This class is used to create a TCP or UNIX server. A server is a n t S c e that can listen for new incoming e.okt connections.

,[

],[

])

Begin accepting connections on the specified p r and h s . If the h s is omitted, the server will accept ot ot ot connections directed to any IPv4 address ( I A D _ N ). A port value of zero will assign a random port. NDRAY This function is asynchronous. When the server has been bound, 'listening' event will be emitted. the last parameter l s e i g i t n r will be added as an listener for the 'listening' event. itnnLsee

One issue some users run into is getting E D R N S errors. This means that another server is already running ADIUE

on the requested port. One way of handling this would be to wait a second and then try again. This can be don with
sre.n'ro'ucin(){ evro(err,fntoe

nodej .o g/api/all.h ml

96/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

iecd='ADIUE){ f(.oe=EDRNS' cnoelg'drsnueerig.' osl.o(Adesis,rtyn..) stieu(ucin( eTmotfnto){ sre.ls( evrcoe) sre.itnPR,HS) evrlse(OTOT }00 ,10) } } )

(Note: All sockets in Node set S _ E S A D already) ORUEDR

,[

])

Start a UNIX socket server listening for connections on the given p t . ah This function is asynchronous. When the server has been bound, 'listening' event will be emitted. the last parameter l s e i g i t n r will be added as an listener for the 'listening' event. itnnLsee

()

Stops the server from accepting new connections. This function is asynchronous, the server is finally closed whe the server emits a ' l s ' event. coe

()

Returns the bound address and port of the server as reported by the operating system. Useful to find which por was assigned when giving getting an OS-assigned address. Returns an object with two properties, e.g.
{ades:17001,"ot:11 "drs""2..."pr"22}

Example:
vrsree.raeevrfntosce){ aevr=ntcetSre(ucin(okt sce.n(goben) okted"ody\" } ) /rbarnoot /gaadmpr. sre.itnfnto( evrlse(ucin){ ades=sre.drs( drsevrades) cnoelg"pndsren%"drs) osl.o(oeeevroj,ades } )

Don't call s r e . d r s ( until the ' i t n n ' event has been emitted. evrades) lseig

Set this property to reject connections when the server's connection count gets high.

nodej .o g/api/all.h ml

97/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

.
The number of concurrent connections on the server.
n t S r e is an E e t m t e with the following events: e.evr vnEitr

:'

'

Emitted when the server has been bound after calling s r e . i t n. evrlse

:'

'

Socket object The connection object Emitted when a new connection is made. s c e is an instance of n t S c e . okt e.okt

:'

'

Emitted when the server closes.

:'
Error Object

'

Emitted when an error occurs. The ' l s ' event will be called directly following this event. See example in coe discussion of s r e . i t n. evrlse

.S

This object is an abstraction of a TCP or UNIX socket. n t S c e instances implement a duplex Stream e.okt and passed to the user through the ' o n c i n event of a server. cneto'

interface. They can be created by the user and used as a client (with c n e t )) or they can be created by Nod onc(

.S

([

])

Construct a new socket object.


o t o s is an object with the following defaults: pin

{f:nl dul tp:nl yeul alwafpnas loHlOe:fle }

f allows you to specify the existing file descriptor of socket. t p specified underlying protocol. It can be d ye

nodej .o g/api/all.h ml

98/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

' c 4 , ' c 6 , or ' n x . About a l w a f p n refer to c e t S r e ( and ' n ' event. tp' tp' ui' loHlOe , raeevr) ed

. .

( (

,[ ,[

],[ L

L ])

])

Opens the connection for a given socket. If p r and h s are given, then the socket will be opened as a TCP ot ot socket, if h s is omitted, l c l o t will be assumed. If a p t is given, the socket will be opened as a unix ot oahs ah socket to that path. Normally this method is not needed, as n t c e t C n e t o opens the socket. Use this only if you are e.raeoncin 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 ' o n c ' event will not be emitted, the ' r o ' event will be emitted with the exception. cnet err The c n e t i t n r parameter will be added as an listener for the 'connect' event. oncLsee

n t S c e has the property that s c e . r t ( always works. This is to help users get up and running e.okt oktwie)

quickly. The computer cannot always keep up with the amount of data that is written to a socket - the network connection simply might be too slow. Node will internally queue up the data written to a socket and send it out over the wire when it is possible. (Internally it is polling on the socket's file descriptor for being writable).

The consequence of this internal buffering is that memory may grow. This property shows the number of characters currently buffered to be written. (Number of characters is approximately equal to the number of byt to be written, but the buffer may contain strings, and the strings are lazily encoded, so the exact number of byte is not known.)

Users who experience large or growing b f e S z should attempt to "throttle" the data flows in their progra ufrie with p u e ) and r s m ( . as( eue)

([

])

Sets the encoding (either ' s i ', ' t 8 , or ' a e 4 ) for data that is received. Defaults to n l . aci uf' bs6' ul

()

This function has been removed in v0.3. It used to upgrade the connection to SSL/TLS. See the TLS section 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.

nodej .o g/api/all.h ml

99/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Returns t u if the entire data was flushed successfully to the kernel buffer. Returns f l e if all or part of th re as data was queued in user memory. ' r i ' will be emitted when the buffer is again free. dan The optional c l b c parameter will be executed when the data is finally written out - this may not be alak immediately.

,[

],[

])

Write data with the optional encoding. The callback will be made when the data is flushed to the kernel.

([

],[

])

Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data. If d t is specified, it is equivalent to calling s c e . r t ( a a n o i g followed by s c e . n ( aa oktwiedt,ecdn) okted)

()

Ensures that no more I/O activity happens on this socket. Only necessary in case of errors (parse error or so).

()

Pauses the reading of data. That is, ' a a events will not be emitted. Useful to throttle back an upload. dt'

()

Resumes reading after a call to p u e ). as(

.
have a timeout.

,[

])

Sets the socket to timeout after t m o t milliseconds of inactivity on the socket. By default n t S c e ieu e.okt

When an idle timeout is triggered the socket will receive a ' i e u ' event but the connection will not be tmot severed. The user must manually e d ) or d s r y ) the socket. n( eto( If t m o t is 0, then the existing idle timeout is disabled. ieu The optional c l b c parameter will be added as a one time listener for the ' i e u ' event. alak tmot

N D

([

])

Disables the Nagle algorithm. By default TCP connections use the Nagle algorithm, they buffer data before

nodej .o g/api/all.h ml

100/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

sending it off. Setting t u for n D l y will immediately fire off data each time s c e . r t ( is called. re oea oktwie)
n D l y defaults to t u . oea re

([

],[

])

Enable/disable keep-alive functionality, and optionally set the initial delay before the first keepalive probe is sen on an idle socket. e a l defaults to f l e. nbe as

Set i i i l e a (in milliseconds) to set the delay between the last data packet received and the first keepaliv ntaDly probe. Setting 0 for initialDelay will leave the value unchanged from the default (or previous) setting. Defaults 0 .

()

Returns the bound address and port of the socket as reported by the operating system. Returns an object with two properties, e.g. { a d e s : 1 2 1 8 5 . " p r " 6 0 3 "drs""9.6.71,"ot:25}

The string representation of the remote IP address. For example, ' 4 1 5 1 7 1 0 or 7.2.2.0'
'0146:05:8 . 20:80a0:6'

The numeric representation of the remote port. For example, 8 or 2 . 0 1

The amount of received bytes.

The amount of bytes sent.


n t S c e instances are EventEmitters with the following events: e.okt

:'

'

Emitted when a socket connection is successfully established. See c n e t ). onc(

:'

'

nodej .o g/api/all.h ml

101/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Buffer object Emitted when data is received. The argument d t will be a B f e or S r n . Encoding of data is set by aa ufr tig
s c e . e E c d n ( . (See the Readable Stream section for more information.) oktstnoig)

Note that the data ill be lost if there is no listener when a S c e emits a ' a a event. okt dt'

:'

'

Emitted when the other end of the socket sends a FIN packet. By default ( a l w a f p n = a s ) the socket will destroy its file descriptor once it has written out its loHlOe=fle pending write queue. However, by setting a l w a f p n = r e the socket will not automatically e d ) loHlOe=tu n( side allowing the user to write arbitrary amounts of data, with the caveat that the user is required to e d ) n( side now.

:'

'

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. See also: s c e . e T m o t ) oktstieu(

:'

'

Emitted when the write buffer becomes empty. Can be used to throttle uploads. See also: the return values of s c e . r t ( oktwie)

:'
Error object

'

Emitted when an error occurs. The ' l s ' event will be called directly following this event. coe

:'

'

h d e r rBoolean true if the socket had a transmission error a_ro

Emitted once the socket is fully closed. The argument h d e r r is a boolean which says if the socket was clos a_ro due to a transmission error.

. IP(

Tests if input is an IP address. Returns 0 for invalid strings, returns 4 for IP version 4 addresses, and returns 6

nodej .o g/api/all.h ml

102/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

for IP version 6 addresses.

. IP 4(

Returns true if input is a version 4 IP address, otherwise returns false.

. IP 6(

Returns true if input is a version 6 IP address, otherwise returns false.

UDP/D
Saiiytbe tblt:3Sal

Datagram sockets are available through r q i e ' g a ' . eur(drm)

,[

])

t p String. Either 'udp4' or 'udp6' ye c l b c Function. Attached as a listener to m s a eevents. Optional alak esg

Returns: Socket object Creates a datagram Socket of the specified types. Valid types are u p and u p . d4 d6 Takes an optional callback which is added as a listener for m s a e events. esg

Call s c e . i d if you want to receive datagrams. s c e . i d ) will bind to the "all interfaces" address o oktbn oktbn( port with s c e . d r s ( . d r s and s c e . d r s ( . o t. oktades)ades oktades)pr

a random port (it does the right thing for both u p and u p sockets). You can then retrieve the address and d4 d6

:S

The dgram Socket class encapsulates the datagram functionality. It should be created via drmcetSce(yeclbc] . ga.raeokttp,[alak)

:'

'

m gBuffer object. The message s r n oObject. Remote address information if

Emitted when a new datagram is available on a socket. m g is a B f e and r n o is an object with the s ufr if sender's address information and the number of bytes in the datagram.

E
nodej .o g/api/all.h ml

:'

'
103/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets are created.

:'

'

Emitted when a socket is closed with c o e ). No new m s a e events will be emitted on this socket. ls( esg

:'

'

e c p i nError object xeto

Emitted when an error occurs.

,[

])

b fBuffer object. Message to be sent u o f e Integer. Offset in the buffer where the message starts. fst l n t Integer. Number of bytes in the message. egh p r Integer. destination port ot a d e sString. destination IP drs c l b c Function. Callback when message is done being delivered. Optional. alak

For UDP sockets, the destination port and IP address must be specified. A string may be supplied for the a d e s parameter, and it will be resolved with DNS. An optional callback may be specified to detect any DNS drs until the next tick. The only way to know for sure that a send has taken place is to use the callback.

errors and when b f may be re-used. Note that DNS lookups will delay the time that a send takes place, at lea u

If the socket has not been previously bound with a call to b n , it's assigned a random port number and bound id to the "all interfaces" address (0.0.0.0 for u p sockets, ::0 for u p sockets). d4 d6 Example of sending a UDP packet to a random port on l c l o t; oahs
vrdrm=rqie'ga' agaeur(drm) vrmsae=nwBfe(Smye" aesgeufr"oebts) vrcinga.raeokt"d4) alet=drmcetSce(up" cin.edmsae,msaelnt,424lclot,fnto(r,bts letsn(esg,0esg.egh13,"oahs"ucinerye){ cin.ls( letcoe) } )

A Note about UDP datagram si e The maximum size of an I v / 6 datagram depends on the M U (Ma imum Transmission Unit) and on the P4v T
P y o d L n t field size. alaegh

The P y o d L n t field is 1 i s wide, which means that a normal payload cannot be larger than alaegh 6bt 64K octets including internet header and data (65,507 bytes = 65,535 8 bytes UDP header 20 bytes IP header); this is generally true for loopback interfaces, but such long datagrams are impractical for most hosts and networks.

nodej .o g/api/all.h ml

104/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The M U is the largest size a given link layer technology can support for datagrams. For any link, I v T P4 mandates a minimum M U of 6 octets, while the recommended M U for IPv4 is 5 6 (typically T 8 T 7 recommended as the M U for dial-up type applications), whether they arrive whole or in fragments. T For I v , the minimum M U is 1 8 octets, however, the mandatory minimum fragment reassembly P6 T 20 buffer size is 1 0 octets. The value of 6 octets is very small, since most current link layer technologies 50 8 have a minimum M U of 1 0 (like Ethernet). T 50

Note that it's impossible to know in advance the MTU of each link through which a packet might travel, and th generally sending a datagram greater than the (receiver) M U won't work (the packet gets silently dropped, T without informing the source that the data did not reach its intended recipient).

.
p r Integer ot

,[

])

a d e sString, Optional drs

For UDP sockets, listen for datagrams on a named p r and optional a d e s. If a d e s is not specified, th ot drs drs OS will try to listen on all addresses. Example of a UDP server listening on port 41234:
vrdrm=rqie"ga" agaeur(drm) vrsrega.raeokt"d4) aevr=drmcetSce(up" sre.n"esg"ucin(s,rno evro(msae,fntomgif){ cnoelg"evrgtsrm"+ osl.o(sreo:"+mg+"fo rnoades+""+rnopr) if.drs:if.ot } ) sre.n"itnn"ucin( evro(lseig,fnto){ vrades=sre.drs( adrsevrades) cnoelg"evrlseig"+ osl.o(sreitnn adesades+""+adespr) drs.drs:drs.ot } ) sre.id424 evrbn(13) /evrlseig0000424 /sreitnn...:13

()

Close the underlying socket and stop listening for data on it.

()

Returns an object containing the address information for a socket. For UDP sockets, this object will contain a d e s and p r . drs ot

nodej .o g/api/all.h ml

105/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

f a Boolean lg

Sets or clears the S _ R A C S socket option. When this option is set, UDP packets may be sent to a local OBODAT interface's broadcast address.

TTL( )

t lInteger t

Sets the I _ T socket option. TTL stands for "Time to Live," but in this context it specifies the number of IP PTL

hops that a packet is allowed to go through. Each router or gateway that forwards a packet decrements the TT 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 s t T ( is a number of hops between 1 and 255. The default on most systems is 64. eTL)

TTL( )

t lInteger t

Sets the I _ U T C S _ T socket option. TTL stands for "Time to Live," but in this context it specifies the PMLIATTL 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 s t u t c s T L ) is a number of hops between 0 and 255. The default on most systems is eMliatT( 64.

f a Boolean lg

Sets or clears the I _ U T C S _ O P socket option. When this option is set, multicast packets will also be PMLIATLO received on the local interface.

,[

])

m l i a t d r s String utcsAdes m l i a t n e f c String, Optional utcsItrae

Tells the kernel to join a multicast group with I _ D _ E B R H P socket option. PADMMESI If m l i a t n e f c is not specified, the OS will try to add membership to all valid interfaces. utcsItrae

nodej .o g/api/all.h ml

106/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

,[

])

m l i a t d r s String utcsAdes m l i a t n e f c String, Optional utcsItrae

Opposite of a d e b r h p - tells the kernel to leave a multicast group with I _ R P M M E S I socket dMmesi PDO_EBRHP 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 m l i a t n e f c is not specified, the OS will try to drop membership to all valid interfaces. utcsItrae

DNS
Saiiytbe tblt:3Sal

Use r q i e ' n ' to access this module. All methods in the dns module use C-Ares except for d s l o u eur(ds) n.okp is more constant with how other programs operate. When a user does n t c n e t 8 , ' o g e c m ) e.onc(0gol.o' of look ups quickly should use the methods that go through C-Ares. Here is an example which resolves ' w . o g e c m then reverse resolves the IP addresses which are wwgol.o' returned.
vrds=rqie'n' aneur(ds) dsrsle(wwgol.o'ucin(r,adess n.eov4'w.ogecm,fntoerdrse){ ierhor f(r)trwer cnoelg'drse:'+JO.tigf(drse) osl.o(adessSNsrniyadess) adessfrahfntoa drse.oEc(ucin(){ dsrvreaucin(r,dmis n.ees(,fntoeroan){ ier f(r){ cnoelg'eesoald osl.o(rvrefr'+a+'fie:'+ ermsae r.esg) }es le{ cnoelg'eeso:'+ osl.o(rvrefr'+a+' JO.tigf(oan) SNsrniydmis) } } ) } ) } )

which uses g t d r n o 3 in a thread pool. C-Ares is much faster than g t d r n o but the system resolve eadif() eadif

h t . e ( o t g o l . o ' } the d s l o u method is used. Users who need to do a large number tpgt{hs:'ogecm) n.okp

,[

],

Resolves a domain (e.g. ' o g e c m ) into the first found A (IPv4) or AAAA (IPv6) record. The f m l gol.o' aiy be the integer 4 or 6. Defaults to n l that indicates both Ip v4 and v6 address family. ul

nodej .o g/api/all.h ml

107/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The callback has arguments ( r , a d e s a i y . The a d e s argument is a string representation of a erdrs,fml) drs IP v4 or v6 address. The f m l argument is either the integer 4 or 6 and denotes the family of a d e s aiy drs necessarily the value initially passed to l o u ). okp

,[

],

Resolves a domain (e.g. ' o g e c m ) into an array of the record types specified by rrtype. Valid rrtypes are gol.o'
' R ' (SRV records), ' T ' (used for reverse IP lookups), ' S (name server records) and ' N M ' SV PR N' CAE

' ' (IPV4 addresses, default), ' A A (IPV6 addresses), ' X (mail exchange records), ' X ' (text records A AA' M' TT

(canonical name records). The callback has arguments ( r , a d e s s . The type of each item in a d e s s is determined by the erdrse) drse record type, and described in the documentation for the corresponding lookup methods below.

On error, e r would be an instanceof E r r object, where e r e r o is one of the error codes listed below an r ro r.rn
e r m s a e is a string describing the error in English. r.esg

4(

The same as d s r s l e ), but only for IPv4 queries ( A records). a d e s s is an array of IPv4 addresses n.eov( drse (e.g. [ 7 . 2 . 9 1 4 , ' 4 1 5 7 . 0 ' 7 . 2 . 9 1 6 ]). '4157.0'7.2.915,'4157.0'

6(

The same as d s r s l e ( except for IPv6 queries (an A A query). n.eov4) AA

M (

The same as d s r s l e ), but only for mail exchange queries ( M records). n.eov( X

a d e s s is an array of MX records, each with a priority and an exchange attribute (e.g. [ ' r o i y : 1 drse {pirt'0 ' x h n e : ' x e a p e c m } . . ). ecag'm.xml.o',.]

T (

The same as d s r s l e ), but only for text queries ( T T records). a d e s s is an array of the text record n.eov( X drse available for d m i (e.g., [ v s f p : . . . a l ]). oan '=p1i40000~l'

S (

The same as d s r s l e ), but only for service records ( S V records). a d e s s is an array of the SRV n.eov( R drse records available for d m i . Properties of SRV records are priority, weight, port, and name (e.g., oan
['roiy:1,{wih','ot:223nm'srieeapecm}.] { p i r t ' 0 ' e g t : 5 p r ' 1 2 , ' a e : ' e v c . x m l . o ' , . . ).

( ,

Reverse resolves an ip address to an array of domain names.

nodej .o g/api/all.h ml

108/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The callback has arguments ( r , d m i s . eroan)

N (

The same as d s r s l e ), but only for name server records ( N records). a d e s s is an array of the n.eov( S drse name server records available for d m i (e.g., [ n 1 e a p e c m , ' s . x m l . o ' ). oan 's.xml.o'n2eapecm]

The same as d s r s l e ), but only for canonical name records ( C A E records). a d e s s is an array of n.eov( NM drse the canonical name records available for d m i (e.g., [ b r e a p e c m ]). oan 'a.xml.o' If there an an error, e r will be non-null and an instanceof the Error object. r Each DNS query can return an error code.
d s T M F I : timeout, SERVFAIL or similar. n.EPAL d s P O O O : got garbled reply. n.RTCL d s N D M I : domain does not exists. n.XOAN d s N D T : domain exists but no data of reqd type. n.OAA d s N M M out of memory while processing. n.OE: d s B D U R : the query is malformed. n.AQEY

HTTP
Saiiytbe tblt:3Sal

To use the HTTP server and client one must r q i e ' t p ). eur(ht' 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. HTTP message headers are represented by an object like this:
{'otnegh:'2' cnetlnt'13, 'otnye:'etpan, cnettp'tx/li' 'oncin:'epaie, cneto'kelv' 'cet:'/'} acp'**

Keys are lowercased. Values are not modified.

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 par the actual headers or the body.

nodej .o g/api/all.h ml

109/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

([

])

Returns a new web server object. The r q e t i t n r is a function which is automatically added to the ' e u s ' event. eusLsee rqet

.S

This is an E e t m t e with the following events: vnEitr

:'

'

fntorqetepne ucin(eus,rsos){}

Emitted each time there is a request. Note that there may be multiple requests per connection (in the case of keep-alive connections). r q e t is an instance of h t . e v r e u s and r s o s is an instance of eus tpSreRqet epne
ht.evrepne tpSreRsos

:'

'

fntosce){} ucin(okt

When a new TCP stream is established. s c e is an object of type n t S c e . Usually users will not want to okt e.okt access this event. The s c e can also be accessed at r q e t c n e t o . okt eus.oncin

:'

'

fnto){} ucin(

Emitted when the server closes.

:'

'

fntorqetepne ucin(eus,rsos){}

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.

Handling this event involves calling r s o s . r t C n i u if the client should continue to send the reques epnewieotne

body, or generating an appropriate HTTP response (e.g., 400 Bad Request) if the client should not continue to send the request body. Note that when this event is emitted and handled, the r q e t event will not be emitted. eus

nodej .o g/api/all.h ml

110/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

:'

'

fntorqetokted ucin(eus,sce,ha){}

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.
r q e tis the arguments for the http request, as it is in the request event. eus s c e is the network socket between the server and client. okt h a is an instance of Buffer, the first packet of the upgraded stream, this may be empty. ed

After this event is emitted, the request's socket will not have a d t event listener, meaning you will need to bin aa to it in order to handle data sent to the server on that socket.

:'

'

fntoecpin ucin(xeto){}

If a client connection emits an 'error' event - it will forwarded here.

,[

],[

])

Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address ( I A D _ N ). NDRAY To listen to a unix socket, supply a filename instead of port and hostname. This function is asynchronous. The last parameter c l b c will be added as a listener for the 'listening' alak See also net.Server.listen().

,[

])

Start a UNIX socket server listening for connections on the given p t . ah This function is asynchronous. The last parameter c l b c will be added as a listener for the 'listening' alak See also net.Server.listen().

()

Stops the server from accepting new connections. See net.Server.close().

.S

This object is created internally by a HTTP server -- not by the user -- and passed as the first argument to a ' e u s ' listener. rqet

nodej .o g/api/all.h ml

111/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The request implements the Readable Stream interface. This is an E e t m t e with the following events: vnEitr

:'

'

fntocuk ucin(hn){}

Emitted when a piece of the message body is received. The chunk is a string if an encoding has been set with r q e t s t n o i g ) otherwise it's a Buffer. eus.eEcdn( , Note that the data ill be lost if there is no listener when a S r e R q e t emits a ' a a event. evreus dt'

:'

'

fnto){} ucin(

Emitted exactly once for each request. After that, no more ' a a events will be emitted on the request. dt'

:'

'

fnto){} ucin(

Indicates that the underlaying connection was terminated before r s o s . n ( was called or able to flush. epneed) Just like ' n ', this event occurs only once per request, and no more ' a a events will fire afterwards. ed dt' Note: ' l s ' can fire after ' n ', but not vice versa. coe ed

.
The request method as a string. Read only. Example: ' E ', ' E E E . GT DLT'

.
Request URL string. This contains only the URL that is present in the actual HTTP request. If the request is:
GT/ttsnm=ynHT/.\\ Esau?aeraTP11rn Acp:tx/li\\ cetetpanrn \\ rn

Then r q e t u l will be: eus.r


'sau?aera' /ttsnm=yn

If you would like to parse the URL into its parts, you can use r q i e ' r ' . a s ( e u s . r ). Examp eur(ul)prerqetul

nodej .o g/api/all.h ml

112/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

nd>rqie'r'.as(/ttsnm=yn) oeeur(ul)pre'sau?aera' {he:'sau?aera' rf/ttsnm=yn, sac:'nm=yn, erh?aera' qeynm=yn, ur:'aera' ptnm:'sau'} ahae/tts

If you would like to extract the params from the query string, you can use the r q i e ' u r s r n ' . a s eur(qeytig)pr function, or pass t u as the second argument to r q i e ' r ' . a s . Example: re eur(ul)pre
nd>rqie'r'.as(/ttsnm=yn,tu) oeeur(ul)pre'sau?aera're {he:'sau?aera' rf/ttsnm=yn, sac:'nm=yn, erh?aera' qeyaera'} ur:{nm:'yn, ptnm:'sau'} ahae/tts

.
Read only.

.
Read only; HTTP trailers (if present). Only populated after the 'end' event.

The HTTP protocol version as a string. Read only. Examples: ' . ', ' . '. Also r q e t h t V r i n a o 11 10 eus.tpesoMj is the first integer and r q e t h t V r i n i o is the second. eus.tpesoMnr

([

])

Set the encoding for the request body. Either ' t 8 or ' i a y . Defaults to n l , which means that the uf' bnr' ul
' a a event will emit a B f e object.. dt' ufr

()

Pauses request from emitting events. Useful to throttle back an upload.

()

Resumes a paused request.

nodej .o g/api/all.h ml

113/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

.
The n t S c e object associated with the connection. e.okt

With HTTPS support, use request.connection.verifyPeer() and request.connection.getPeerCertificate() to obtain the client's authentication details.

.S

This object is created internally by a HTTP server--not by the user. It is passed as the second parameter to the ' e u s ' event. rqet The response implements the Writable Stream interface. This is an E e t m t e with the following events: vnEitr

:'

'

fnto){} ucin(

Indicates that the underlaying connection was terminated before r s o s . n ( was called or able to flush. epneed)

()

Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the checkContinue event on S r e . evr

,[

],[

])

Sends a response header to the request. The status code is a 3-digit HTTP status code, like 4 4. The last 0 argument, h a e s, are the response headers. Optionally one can give a human-readable r a o P r s edr esnhae second argument. Example:
vrbdhlowrd aoy='elol' rsos.rtHa(0,{ epnewieed20 'otnegh:bd.egh CnetLnt'oylnt, 'otnye:'etpan) CnetTp'tx/li'}

This method must only be called once on a message and it must be called before r s o s . n ( is called. epneed) If you call r s o s . r t ( or r s o s . n ( before calling this, the implicit/mutable headers will be epnewie) epneed) calculated and call this function for you. Note: that Content-Length is given in bytes not characters. The above example works because the string
w r d contains only single byte characters. If the body contains higher coded characters then ol' B f e . y e e g h ) should be used to determine the number of bytes in a given encoding. And Node does ufrbtLnt(

not check whether Content-Length and the length of the body which has been transmitted are equal or not.

nodej .o g/api/all.h ml

114/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

When using implicit headers (not calling r s o s . r t H a ( explicitly), this property controls the status epnewieed) code that will be send to the client when the headers get flushed. Example:
rsos.ttsoe=44 epnesauCd0

After response header was sent to the client, this property indicates the status code which was sent out.

Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name. Example:
rsos.eHae(CnetTp"tx/tl) epnestedr"otnye,"ethm"

or
rsos.eHae(StCoi""yenna,"agaejvsrp") epnestedr"eoke,[tp=ij"lnug=aacit]

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:
vrcnetye=rsos.eHae(cnettp' aotnTpepnegtedr'otnye)

.
Example:

Removes a header that's queued for implicit sending.

rsos.eoeedr"otnnoig) epnermvHae(CnetEcdn"

,[

])

nodej .o g/api/all.h ml

115/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

If this method is called and r s o s . r t H a ( has not been called, it will switch to implicit header mode epnewieed) and flush the implicit headers. This sends a chunk of the response body. This method may be called multiple times to provide successive parts the body.
c u k can be a string or a buffer. If c u k is a string, the second parameter specifies how to encode it into a hn hn

byte stream. By default the e c d n is ' t 8 . noig uf' Note: This is the raw HTTP body and has nothing to do with higher-level multi-part body encodings that may used.

The first time r s o s . r t ( is called, it will send the buffered header information and the first body to th epnewie) client. The second time r s o s . r t ( is called, Node assumes you're going to be streaming data, and epnewie) sends that separately. That is, the response is buffered up to the first chunk of body.

This method adds HTTP trailing headers (a header but at the end of the message) to the response. Trailers will onl 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 T a l r header to be sent if you intend to emit trailers, with a list of the header rie fields in its value. E.g.,
rsos.rtHa(0,{'otnye:'etpan, epnewieed20CnetTp'tx/li' 'rie'CnetM5) Talr:'otnD'} rsos.rt(ieaa epnewieflDt) rsos.dTalr('otnD'79b482b5ef74bba6") epneadries{CnetM5:"85fb885ca4774c67} rsos.n( epneed)

([

],[

])

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, r s o s . n ( , MUST be called on each response. epneed) If d t is specified, it is equivalent to calling r s o s . r t ( a a n o i g followed by aa epnewiedt,ecdn)
rsos.n( . epneed)

Node maintains several connections per server to make HTTP requests. This function allows one to transparent issue requests. o t o s align with url.parse(). pin Options:

nodej .o g/api/all.h ml

116/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

h s : A domain name or IP address of the server to issue the request to. Defaults to ' o a h s ' ot lclot. h s n m : To support u l p r e )h s n m is preferred over h s otae r.as( otae ot p r : Port of remote server. Defaults to 80. ot s c e P t : Unix Domain Socket (use one of host:port or socketPath) oktah m t o : A string specifying the HTTP request method. Defaults to ' E ' ehd GT. p t : Request path. Defaults to ' ' Should include query string if any. E.G. ' i d x h m ? a e 1 ' ah /. /ne.tlpg=2 h a e s An object containing request headers. edr: a t : Basic authentication i.e. ' s r p s w r 'to compute an Authorization header. uh ue:asod

a e t Controls Agent behavior. When an Agent is used request will default to C n e t o : k e l v gn: oncinepaie

Possible values:
u d f n d(default): use global Agent for this host and port. neie A e tobject: explicitly use the passed in A e t gn gn. f l e opts out of connection pooling with an Agent, defaults request to C n e t o : c o e as: oncinls h t . e u s ( returns an instance of the h t . l e t e u s class. The C i n R q e t instance is a tprqet) tpCinRqet leteus

writable stream. If one needs to upload a file with a POST request, then write to the C i n R q e t object. leteus Example:
vrotos={ apin hs:'w.ogecm, otwwgol.o' pr:8, ot0 pt:'ula' ah/pod, mto:'OT ehdPS' } vrrq=ht.eus(pin,fnto(e){ aetprqetotosucinrs cnoelg'TTSe.ttsoe osl.o(SAU:'+rssauCd) cnoelg'EDR:'+JO.tigf(e.edr) osl.o(HAESSNsrniyrshaes) rsstnoig't8) e.eEcdn(uf' rso(dt'ucin(hn){ e.n'aa,fntocuk cnoelg'OYhn) osl.o(BD:'+cuk } ) } ) rqo(err,fnto(){ e.n'ro'ucine cnoelg'rbeihrqet.esg) osl.o(polmwteus:'+emsae } ) /rtaateusoy /wiedtorqetbd rqwie'aan) e.rt(dt\' rqwie'aan) e.rt(dt\' rqed) e.n(

Note that in the example r q e d ) was called. With h t . e u s ( one must always call r q e d ) e.n( tprqet) e.n( 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 ' r o ' event is emitted on the returned request object. err There are a few special headers that should be noted.

nodej .o g/api/all.h ml

117/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Sending a 'Connection: keep-alive' will notify Node that the connection to the server should be persisted until the next request. Sending a 'Content-length' header will disable the default chunked encoding. Sending an 'Expect' header will immediately send the request headers. Usually, when sending 'Expect: 10 continue', you should both set a timeout and listen for the c n i u event. See RFC2616 Section 8.2.3 for otne more information. Sending an Authorization header will override using the a t option to compute basic authentication. uh

Since most requests are GET requests without bodies, Node provides this convenience method. The only difference between this method and h t . e u s ( is that it sets the method to GET and calls r q e d ) tprqet) e.n( automatically. Example:
vrotos={ apin hs:'w.ogecm, otwwgol.o' pr:8, ot0 pt:'idxhm' ah/ne.tl } ht.e(pin,fnto(e){ tpgtotosucinrs cnoelg"oepnee.ttsoe osl.o(Gtrsos:"+rssauCd) }.n'ro'ucine )o(err,fnto(){ cnoelg"oro:"+emsae osl.o(Gterr.esg) } )

.A

In node 0.5.3+ there is a new implementation of the HTTP Agent which is used for pooling sockets used in HTT client requests. Previously, a single agent instance help the pool for single host+port. The current implementation now holds sockets for any number of hosts.

The current HTTP Agent also defaults client requests to using Connection:keep-alive. If no pending HTTP requests are waiting on a socket to become free the socket is closed. This means that node's pool has the benefit of keep-alive when under load but still does not require developers to manually close the HTTP clients using keep-alive. Sockets are removed from the agent's pool when the socket emits either a "close" event or a special "agentRemove" event. This means that if you intend to keep one HTTP request open for a long time and don't want it to stay in the pool you can do something along the lines of:
ht.e(pin,fnto(e){ tpgtotosucinrs /osuf /Dtf }.n"okt,fntosce){ )o(sce"ucin(okt sce.mt"gnRmv" oktei(aeteoe)

nodej .o g/api/all.h ml

118/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

} )

Alternatively, you could just opt out of pooling entirely using a e t f l e: gn:as
ht.e(hs:lclot,pr:0ah''gn:as}ucin(e){ tpgt{ot'oahs'ot8,pt:/,aetfle,fntors /osuf /Dtf } )

By default set to 5. Determines how many concurrent sockets the agent can have open per host.

.
An object which contains arrays of sockets currently in use by the Agent. Do not modify.

.
An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.

Global instance of Agent which is used as the default for all http client requests.

.C

This object is created internally and returned from h t . e u s ( . It represents an in-progress request whos tprqet) header has already been queued. The header is still mutable using the s t e d r n m , v l e , eHae(aeau)
g t e d r n m ) r m v H a e ( a e API. The actual header will be sent along with the first data chunk eHae(ae , eoeedrnm)

when closing the connection.

To get the response, add a listener for ' e p n e to the request object. ' e p n e will be emitted from the rsos' rsos' request object when the response headers have been received. The ' e p n e event is executed with one rsos' argument which is an instance of h t . l e t e p n e. tpCinRsos During the ' e p n e event, one can add listeners to the response object; particularly to listen for the rsos' event. Note that the ' e p n e event is called before any part of the response body is received, so there is no rsos' need to worry about racing to catch the first part of the body. As long as a listener for ' a a is added during dt' the ' e p n e event, the entire body will be caught. rsos'
/od /Go rqeto(rsos'ucin(epne eus.n'epne,fntorsos){ rsos.n'aa,fntocuk epneo(dt'ucin(hn){ cnoelg'OYhn) osl.o(BD:'+cuk } )

nodej .o g/api/all.h ml

119/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

} ) /aissaloatohoy /Bdmselrprftebd rqeto(rsos'ucin(epne eus.n'epne,fntorsos){ stieu(ucin( eTmotfnto){ rsos.n'aa,fntocuk epneo(dt'ucin(hn){ cnoelg'OYhn) osl.o(BD:'+cuk } ) }0 ,1) } )

Note: Node does not check whether Content-Length and the length of the body which has been transmitted ar equal or not. The request implements the Writable Stream interface. This is an E e t m t e with the following events: vnEitr

'

'

fntorsos){} ucin(epne

Emitted when a response is received to this request. This event is emitted only once. The r s o s argument w epne be an instance of h t . l e t e p n e. tpCinRsos Options:
h s : A domain name or IP address of the server to issue the request to. ot p r : Port of remote server. ot s c e P t : Unix Domain Socket (use one of host:port or socketPath) oktah

:'

'

fntosce){} ucin(okt

Emitted after a socket is assigned to this request.

:'

'

fntorsos,sce,ha){} ucin(epneokted

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. A client server pair that show you how to listen for the u g a e event using h t . e A e t: prd tpgtgn
vrhteur(ht' atp=rqie'tp) vrnt=rqie'e' aeeur(nt)

nodej .o g/api/all.h ml

120/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

/raeaTPsre /CetnHTevr vrsv=ht.raeevrfntorqe){ artpcetSre(ucin(e,rs rswieed20'otnye:'etpan} e.rtHa(0,{CnetTp'tx/li') rsed'ky) e.n(oa' } ) svo(ugae,fnto(e,sce,ugaeed r.n'prd'ucinrqoktprdHa){ sce.rt(HT/.0eoktPoooadhk\\'+ oktwie'TP1111WbScertclHnsaern UgaeeSce\\'+ 'prd:Wboktrn Cneto:Ugaern 'oncinprd\\'+ \\\\' 'rnrn) sce.naa=fnto(aatr,ed oktodtucindt,satn){ sce.rt(aatSrn(uf'tr,ed,'t8)/ehak oktwiedt.otig't8,satn)uf'/cobc } } ) /ohtsresrnig /nwtaevriunn svlse(3717001,fnto( r.itn13,'2...'ucin){ /aearqet /mkeus vrotos={ apin pr:13, ot37 hs:'2...' ot17001, haes edr:{ 'oncin:'prd' Cneto'Ugae, 'prd'wbokt Ugae:'esce' } } vrrq=ht.eus(pin) aetprqetotos rqed) e.n( rqo(ugae,fnto(e,sce,ugaeed e.n'prd'ucinrsoktprdHa){ cnoelg'oprdd' osl.o(gtugae!) sce.n( okted) poesei() rcs.xt0 } ) } )

:'

'

fnto){} ucin(

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.

,[

])

Sends a chunk of the body. By calling this method many times, the user can stream a request body to a server-that case it is suggested to use the [ T a s e n o i g , ' h n e ' header line when creating the reque 'rnfrEcdn'cukd]

nodej .o g/api/all.h ml

121/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The c u k argument should be a buffer or a string. hn The e c d n argument is optional and only applies when c u k is a string. Defaults to ' t 8 . noig hn uf'

([

],[

])

Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream. If the request chunked, this will send the terminating ' \ \ \ \ '. 0rnrn

If d t is specified, it is equivalent to calling r q e t w i e d t , e c d n ) followed by r q e t e d ) aa eus.rt(aanoig eus.n(

()

Aborts a request. (New since v0.3.8.)

,[

])

Once a socket is assigned to this request and is connected socket.setTimeout(timeout, [callback]) will be called.

N D

([

])

Once a socket is assigned to this request and is connected socket.setNoDelay(noDelay) will be called.

([

],[

])

Once a socket is assigned to this request and is connected socket.setKeepAlive(enable, [initialDelay]) will be called.

.C
request object.

This object is created when making a request with h t . e u s ( . It is passed to the ' e p n e event of th tprqet) rsos'

The response implements the Readable Stream interface. This is an E e t m t e with the following events: vnEitr

:'

'

fntocuk ucin(hn){}

Emitted when a piece of the message body is received. Note that the data ill be lost if there is no listener when a C i n R s o s emits a ' a a event. letepne dt'

nodej .o g/api/all.h ml

122/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

:'

'

fnto){} ucin(

Emitted exactly once for each message. No arguments. After emitted no other events will be emitted on the response.

:'

'

fntoer ucin(r){}

Indicates that the underlaying connection was terminated before e d event was emitted. See n http.ServerRequest's ' l s ' event for more information. coe

The 3-digit HTTP response status code. E.G. 4 4. 0

The HTTP version of the connected-to server. Probably either ' . ' or ' . '. Also 11 10
r s o s . t p e s o M j r is the first integer and r s o s . t p e s o M n r is the second. epnehtVrinao epnehtVrinio

.
The response headers object.

.
The response trailers object. Only populated after the 'end' event.

([

])

Set the encoding for the response body. Either ' t 8 , ' s i ', or ' a e 4 . Defaults to n l , which mea uf' aci bs6' ul that the ' a a event will emit a B f e object. dt' ufr

()

Pauses response from emitting events. Useful to throttle back a download.

.
Resumes a paused response.

()

nodej .o g/api/all.h ml

123/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

HTTPS
Saiiytbe tblt:3Sal

HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a separate module.

.S

This class is a subclass of t s S r e and emits events same as h t . e v r. See h t . e v r for more l.evr tpSre tpSre information.

,[

])

Returns a new HTTPS web server object. The o t o s is similar to t s c e t S r e ( . The pin l.raeevr)
r q e t i t n r is a function which is automatically added to the ' e u s ' event. eusLsee rqet

Example:
/ultp:/oahs:00 /crkhts/lclot80/ vrhts=rqie'tp' atpeur(hts) vrfeur(f' as=rqie's) vrotos={ apin kysraFlSn(ts/itrsky/gn2kypm) e:f.edieyc'etfxue/esaete.e', cr:f.edieyc'etfxue/esaetetpm) etsraFlSn(ts/itrsky/gn2cr.e' } htscetSre(pin,fntorqe){ tp.raeevrotosucin(e,rs rswieed20 e.rtHa(0) rsed"elol\" e.n(hlowrdn) }.itn80) )lse(00

.
Example:

Makes a request to a secure web server. All options from http.request() are valid.

vrhts=rqie'tp' atpeur(hts) vrotos={ apin hs:'nrpe.ogecm, otecytdgol.o' pr:43 ot4, pt:'' ah/, mto:'E' ehdGT } vrrq=htsrqetotosucinrs aetp.eus(pin,fnto(e){

nodej .o g/api/all.h ml

124/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelg"ttsoe,rssauCd) osl.o(sauCd:"e.ttsoe cnoelg"edr:"e.edr) osl.o(haes,rshaes rso(dt'ucind e.n'aa,fnto(){ poessdu.rt() rcs.totwied } ) } ) rqed) e.n( rqo(err,fnto(){ e.n'ro'ucine cnoeerre osl.ro() } )

The options argument has the following options host: IP or domain of host to make request to. Defaults to ' o a h s ' lclot. port: port of host to request to. Defaults to 443. path: Path to request. Default ' ' /. method: HTTP request method. Default ' E '. GT
h s : A domain name or IP address of the server to issue the request to. Defaults to ' o a h s ' ot lclot h s n m : To support u l p r e )h s n m is preferred over h s otae r.as( otae ot p r : Port of remote server. Defaults to 443. ot m t o : A string specifying the HTTP request method. Defaults to ' E ' ehd GT. p t : Request path. Defaults to ' ' Should include query string if any. E.G. ' i d x h m ? a e 1 ' ah /. /ne.tlpg=2 h a e s An object containing request headers. edr: a t : Basic authentication i.e. ' s r p s w r 'to compute an Authorization header. uh ue:asod

a e t Controls Agent behavior. When an Agent is used request will default to C n e t o : k e l v gn: oncinepaie

Possible values:
u d f n d(default): use globalAgent for this host and port. neie A e tobject: explicitly use the passed in A e t gn gn. f l e opts out of connection pooling with an Agent, defaults request to C n e t o : c o e as: oncinls

The following options from tls.connect() can also be specified. However, a globalAgent silently ignores these.
k y Private key to use for SSL. Default n l . e: ul p s p r s : A string of passphrase for the private key. Default n l . ashae ul c r : Public x509 certificate to use. Default n l . et ul c : An authority certificate or array of authority certificates to check the remote host against. a

In order to specify these options, use a custom A e t. gn Example:


vrotos={ apin hs:'nrpe.ogecm, otecytdgol.o' pr:43 ot4, pt:'' ah/, mto:'E' ehdGT, kysraFlSn(ts/itrsky/gn2kypm) e:f.edieyc'etfxue/esaete.e', cr:f.edieyc'etfxue/esaetetpm) etsraFlSn(ts/itrsky/gn2cr.e' }

nodej .o g/api/all.h ml

125/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

otosaet=nwhtsAetotos pin.gnetp.gn(pin) vrrq=htsrqetotosucinrs aetp.eus(pin,fnto(e){ .. . }

Or does not use an A e t. gn Example:


vrotos={ apin hs:'nrpe.ogecm, otecytdgol.o' pr:43 ot4, pt:'' ah/, mto:'E' ehdGT, kysraFlSn(ts/itrsky/gn2kypm) e:f.edieyc'etfxue/esaete.e', cr:f.edieyc'etfxue/esaetetpm) etsraFlSn(ts/itrsky/gn2cr.e', aetas gn:fle } vrrq=htsrqetotosucinrs aetp.eus(pin,fnto(e){ .. . }

.
Example:

Like h t . e ( but for HTTPS. tpgt)

vrhts=rqie'tp' atpeur(hts) htsgt{hs:'nrpe.ogecm,pt:''}ucinrs tp.e(otecytdgol.o'ah/,fnto(e){ cnoelg"ttsoe,rssauCd) osl.o(sauCd:"e.ttsoe cnoelg"edr:"e.edr) osl.o(haes,rshaes rso(dt'ucind e.n'aa,fnto(){ poessdu.rt() rcs.totwied } ) }.n'ro'ucine )o(err,fnto(){ cnoeerre osl.ro() } )

.A

An Agent object for HTTPS similar to http.Agent. See https.request() for more information.

nodej .o g/api/all.h ml

126/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Global instance of https.Agent which is used as the default for all HTTPS client requests.

URL
Saiiytbe tblt:3Sal

This module has utilities for URL resolution and parsing. Call r q i e ' r ' to use it. eur(ul)

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 UR
'tp/ue:ashs.o:00pathqeysrn#ah ht:/srps@otcm88////?ur=tighs' h e : The full URL that was originally parsed. Both the protocol and host are lowercased. rf

Example: ' t p / u e : a s h s . o : 0 0 p a t h q e y s r n # a h ht:/srps@otcm88////?ur=tighs'


p o o o : The request protocol, lowercased. rtcl

Example: ' t p ' ht:


h s : The full lowercased host portion of the URL, including port and authentication information. ot

Example: ' s r p s @ o t c m 8 8 ' ue:ashs.o:00


a t : The authentication information portion of a URL. uh

Example: ' s r p s ' ue:as


h s n m : Just the lowercased hostname portion of the host. otae

Example: ' o t c m hs.o'


p r : The port number portion of the host. ot

Example: ' 0 0 88'


p t n m : The path section of the URL, that comes after the host and before the query, including the ahae

initial slash if present. Example: ' p a t h ////'


s a c : The 'query string' portion of the URL, including the leading question mark. erh

Example: ' q e y s r n ' ?ur=tig


p t : Concatenation of p t n m and s a c . ah ahae erh

Example: ' p a t h q e y s r n ' ////?ur=tig


q e y Either the 'params' portion of the query string, or a querystring-parsed object. ur :

Example: ' u r = t i g or { q e y : s r n ' qeysrn' 'ur''tig}


h s : The 'fragment' portion of the URL including the pound-sign. ah

nodej .o g/api/all.h ml

127/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Example: ' h s ' #ah The following methods are provided by the URL module:

S ,[

],[

])

Take a URL string, and return an object. Pass t u as the second argument to also parse the query string using the q e y t i g module. Defaults to re ursrn
fle as .

Pass t u as the third argument to treat / f o b r as { h s : ' o ' a h a e / a ' } rather than re /o/a otfo,ptnm:'br
p t n m : ' / o / a ' } Defaults to f l e ahae/fobr . as .

O )

Take a parsed URL object, and return a formatted URL string.


h e will be ignored. rf p o o o is treated the same with or without the trailing :(colon). rtcl

The protocols h t , h t s f p g p e , f l will be postfixed with : /(colon-slash-slash). tp tp, t, ohr ie / All other protocols m i t , x p , a m s t , f o etc will be postfixed with :(colon) alo mp i, fp o,
a t will only be used if h s is absent. uh ot h s n m will only be used if h s is absent. otae ot p r will only be used if h s is absent. ot ot h s will be used in place of a t , h s n m , and p r ot uh otae ot p t n m is treated the same with or without the leading /(slash) ahae s a c will be used in place of q e y erh ur q e y(object; see q e y t i g will only be used if s a c is absent. ur ursrn) erh s a c is treated the same with or without the leading ?(question mark) erh h s is treated the same with or without the leading #(pound sign, anchor) ah

, )

Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.

Saiiytbe tblt:3Sal

This module provides utilities for dealing with query strings. It provides the following methods:

.
characters.

,[

],[

])

Serialize an object to a query string. Optionally override the default separator ( ' ') and assignment ( ' ' & =

nodej .o g/api/all.h ml

128/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Example:
qeytigsrniy{fobr,bz'u'qu',cre'} ursrn.tigf(o:'a'a:[qx,'ux]og:') /eun /rtrs 'o=a&a=u&a=uxcre' fobrbzqxbzqu&og= qeytigsrniy{o:'a'a:'u','':) ursrn.tigf(fobr,bzqx},'' /eun /rtrs 'o:aa:u' fobrbzqx

.
characters. Example:

,[

],[

])

Deserialize a query string to an object. Optionally override the default separator ( ' ') and assignment ( &

qeytigpre'o=a&a=u&a=uxcre) ursrn.as(fobrbzqxbzqu&og' /eun /rtrs {fobr,bz'u'qu',cre'} o:'a'a:[qx,'ux]og:'

.
The escape function used by q e y t i g s r n i y, provided so that it could be overridden if necessary. ursrn.tigf

.
The unescape function used by q e y t i g p r e, provided so that it could be overridden if necessary. ursrn.as

R
Saiiytbe tblt:3Sal

To use this module, do r q i e ' e d i e ). Readline allows reading of a stream (such as STDIN) on a line eur(raln' by-line basis. Note that once you've invoked this module, your node program will not terminate until you've closed the interface, and the STDIN stream. Here's how to allow your program to gracefully terminate:
vrreur(raln' al=rqie'edie) vri=r.raenefc(rcs.ti,poessdu,nl) alcetItraepoessdnrcs.totul iqeto(Waoyutikooej?,fnto(nwr .usin"htdohnfnd.s"ucinase){ /OOohnwriaaae /TD:Lgteasenadtbs cnoelg"hnooorvlaledak" osl.o(Takyufryuaubefebc.)

nodej .o g/api/all.h ml

129/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

/hswieoehralwtepormtemnt.Wtot /Teetolnstgtelohrgaotriaeihu /hmtwudrnfrvr /te,ioluoee. icoe) .ls( poessdndsry) rcs.ti.eto( } )

Takes two streams and creates a readline interface. The c m l t r function is used for autocompletion. When opee given a substring, it returns [ s b t 1 u s r , . . , o i i a s b t i g . [usr,sbt2.]rgnlusrn] Also c m l t r can be run in async mode if it accepts two arguments: opee function completer(linePartial, callback) { callback(null, [['123'], linePartial]); }

c e t I t r a e is commonly used with p o e s s d n and p o e s s d u in order to accept user inpu raenefc rcs.ti rcs.tot

vrralneur(raln', aedie=rqie'edie) rediecetItraepoessdnrcs.tot l=raln.raenefc(rcs.ti,poessdu)

:I

The class that represents a readline interface with a stdin and stdout stream.

Sets the prompt, for example when you run n d on the command line, you see > , which is node's prompt. oe

()

Readies readline for input from the user, putting the current s t r m t options on a new line, giving the user ePop new spot to write.

Prepends the prompt with q e y and invokes c l b c with the user's response. Displays the query to the us ur alak and then invokes c l b c with the user's response after it has been typed. alak Example usage:
itraeqeto(Wasyuaoiefo?,fnto(nwr nefc.usin'htiorfvrtod'ucinase){ cnoelg'hoyuaoiefos'+ase) osl.o(O,sorfvrtodinwr } )

nodej .o g/api/all.h ml

130/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

.
Closes tty.

()

.
Pauses tty.

()

.
Resumes tty.

()

()

Writes to tty.

:'

'

fntoln){ ucin(ie}

Emitted whenever the i stream receives a \ , usually received when the user hits enter, or return. This is a n n good hook to listen for user input. Example of listening for l n : ie
r.n'ie,fntocd lo(ln'ucin(m){ cnoelg'outtpd+m) osl.o(Yujsye:'cd } )

:'

'

fnto){ ucin(}

Emitted whenever the i stream receives a ^ or ^ , respectively known as S G N and E T. This is a good n C D IIT O way to know the user is finished using your program. Example of listening for c o e, and exiting the program afterward: ls
r.n'ls'ucin){ lo(coe,fnto( cnoelg'ody!) osl.o(gobe' poesei() rcs.xt0 } )

Here's an example of how to use all these together to craft a tiny command line interface:

nodej .o g/api/all.h ml

131/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

vrralneur(raln', aedie=rqie'edie) rediecetItraepoessdnrcs.tot, l=raln.raenefc(rcs.ti,poessdu) peiOA>' rfx='HI r.n'ie,fnto(ie lo(ln'ucinln){ sic(ieti(){ wthln.rm) cshlo: ae'el' cnoelg'ol!) osl.o(wrd' bek ra dfut eal: cnoelg'ahtihaehad`ieti(`) osl.o(Sywa?Imgthver'+ln.rm)+'' bek ra } r.ePop(rfxrfxlnt) lstrmtpei,pei.egh r.rmt) lpop( }.n'ls'ucin){ )o(coe,fnto( cnoelg'aeagetdy' osl.o(Hvraa!) poesei() rcs.xt0 } ) cnoelgpeiGooseyuryigsuf' osl.o(rfx+'odteo.Tytpntf.) r.ePop(rfxrfxlnt) lstrmtpei,pei.egh r.rmt) lpop(

Take a look at this slightly more complicated example, and http-console for a real-life use case.

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 debuggin testing, or just trying things out. By executing n d without any arguments from the command-line you will be dropped into the REPL. It has oe simplistic emacs line-editing.
mr~oe j:$nd Tp.epopin. ye'hl'frotos >a=[1,3 ,2] [1,3] ,2 >afrahfntov .oEc(ucin(){ ..cnoelgv .osl.o() ..} .) 1 2 3

For advanced line-editors, start node with the environmental variable N D _ O R A L N = . This will start the OEN_EDIE1 REPL in canonical terminal settings which will allow you to use with r w a . lrp For example, you could add this to your bashrc file:

nodej .o g/api/all.h ml

132/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

aisnd=evND_ORALN=lrpnd" laoe"nOEN_EDIE1rwaoe

([

],[ ])

],[

],[

],

Starts a REPL with p o p as the prompt and s r a for all I/O. p o p is optional and defaults to rmt tem rmt
s r a is optional and defaults to p o e s s d n e a is optional too and defaults to async wrapper for tem rcs.ti . vl ea( . vl)

If u e l b l is set to true, then the repl will use the global object, instead of running scripts in a separate sGoa context. Defaults to f l e. as If i n r U d f n d is set to true, then the repl will not output return value of command if it's u d f n d goeneie neie Defaults to f l e. as You can use your own e a function if it has following signature: vl
fntovlcdalak ucinea(m,clbc){ clbc(uleut alaknl,rsl) }

Multiple REPLs may be started against the same running instance of node. Each will share the same global object but will have unique I/O. Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:
vrnt=rqie"e", aeeur(nt) rpeur(rp" el=rqie"el) cnetos=0 oncin rp.tr(nditi>" elsat"oevasdn) ntcetSre(ucin(okt e.raeevrfntosce){ cnetos+ oncin=1 rp.tr(ndinxsce>"okt elsat"oevaUiokt,sce) }.itn"tpndelsc" )lse(/m/oerpok) ntcetSre(ucin(okt e.raeevrfntosce){ cnetos+ oncin=1 rp.tr(ndiCokt,sce) elsat"oevaTPsce>"okt }.itn50) )lse(01

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. t l e is useful for connecting to TCP sockets, and s c t can be use ent oa 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

nodej .o g/api/all.h ml

133/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

process without restarting it.

REPLF

Inside the REPL, Control+D will exit. Multi-line expressions can be input. Tab completion is supported for both global and local variables. The special variable _ (underscore) contains the result of the last expression.
>[""b,""] a,""c [''b,''] a,''c >_lnt .egh 3 >_+ =1 4

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 c n e t object associated with each R P S r e . For example: otx ELevr
/elts.s /rp_etj vrrpeur(rp", ael=rqie"el) mg="esg" smsae rp.tr(.otx.s elsat)cnetm=mg

Things in the c n e t object appear as local within the REPL: otx


mr~oerp_etj j:$ndelts.s >m 'esg' msae

There are a few special REPL commands:


. r a - While inputting a multi-line expression, sometimes you get lost or just don't care about bek

completing it. . r a will start over. bek


. l a - Resets the c n e tobject to an empty object and clears any multi-line expression. cer otx . x t- Close the I/O stream, which will cause the REPL to exit. ei . e p- Show this list of special commands. hl . a e- Save the current REPL session to a file sv

.save ./file/to/save.js
. o d- Load a file into the current REPL session. la

.load ./file/to/load.js The following key combinations in the REPL have these special effects:

< t l C- Similar to the . r a keyword. Terminates the current command. Press twice on a blank line to cr> bek

nodej .o g/api/all.h ml

134/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

forcibly exit. < t l D- Similar to the . x tkeyword. cr> ei

J
Saiiytbe tblt:3Sal

You can access this module with:


vrveur(v' am=rqie'm)

JavaScript code can be compiled and run immediately or compiled, saved, and run later.

I T

,[

])

v . u I T i C n e t ) compiles c d , runs it and returns the result. Running code does not have access to mrnnhsotx( oe

local scope. f l n m is optional, it's used only in stack traces. ieae Example of using v . u I T i C n e t and e a to run the same code: mrnnhsotx vl
vrlcla2, aoaVr=13 uigcitvld snsrp,eae, veur(v' m=rqie'm) uigcit=v.uITiCnet'oaVr=1' snsrpmrnnhsotx(lcla, 'yiev' mfl.m) cnoelg'oaVroaVr+'snsrp:'+ osl.o(lcla:'+lcla,uigcit uigcit snsrp) eaevl'oaVr=1' vld=ea(lcla) cnoelg'oaVroaVr+'vld osl.o(lcla:'+lcla,eae:'+ eae) vld /oaVr2,uigcit /lcla:13snsrp:1 /oaVr,eae:1 /lcla:1vld

v . u I T i C n e t does not have access to the local scope, so l c l a is unchanged. e a does have mrnnhsotx oaVr vl

access to the local scope, so l c l a is changed. oaVr In case of syntax error in c d , v . u I T i C n e t emits the syntax error to stderr and throws an oe mrnnhsotx exception.

I N

,[

],[

])

v . u I N w o t x compiles c d , then runs it in s n b x and returns the result. Running code does not mrnneCnet oe ado

have access to local scope. The object s n b x will be used as the global object for c d . s n b x and ado oe ado
f l n m are optional, f l n m is only used in stack traces. ieae ieae

nodej .o g/api/all.h ml

135/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Example: compile and execute code that increments a global variable and sets a new one. These globals are contained in the sandbox.
vruieur(ui', atl=rqie'tl) veur(v', m=rqie'm) snbx={ ado aia:'a' nmlct, cut on:2 } v.uINwotx(cut+nmkty'ado,'yiev' mrnneCnet'on=1ae="it",snbxmfl.m) cnoelgui.npc(ado) osl.o(tlisetsnbx) /nmlct,cut,nm:'it'} /{aia:'a'on:3aekty

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, v . u I N w o t x is quite useful, but safely running untrusted code requires a separate process. mrnneCnet

In case of syntax error in c d , v . u I N w o t x emits the syntax error to stderr and throws an exceptio oe mrnneCnet

I C

,[

])

v . u I C n e t compiles c d , then runs it in c n e t and returns the result. A (V8) context comprises a mrnnotx oe otx

global object, together with a set of built-in objects and functions. Running code does not have access to local scope and the global object held within c n e t will be used as the global object for c d . f l n m is otx oe ieae optional, it's used only in stack traces. Example: compile and execute code in a existing context.
vruieur(ui', atl=rqie'tl) veur(v', m=rqie'm) iiSnbx={ ntado aia:'a' nmlct, cut on:2 } , cnet=v.raeotx(ntado) otxmcetCnetiiSnbx v.uICnet'on=1ae="AT'otx,'yiev' mrnnotx(cut+nmCT",cnetmfl.m) cnoelgui.npc(otx) osl.o(tlisetcnet) /nmlct,cut,nm:'AT /{aia:'a'on:3aeCT'}

Note that c e t C n e t will perform a shallow clone of the supplied sandbox object in order to initialise the raeotx global object of the freshly constructed context.

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, v . u I C n e t is quite useful, but safely running untrusted code requires a separate process. mrnnotx In case of syntax error in c d , v . u I C n e t emits the syntax error to stderr and throws an exception. oe mrnnotx

nodej .o g/api/all.h ml

136/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

([

])

v . r a e o t x creates a new context which is suitable for use as the 2nd argument of a subsequent call to mcetCnet

v . u I C n e t A (V8) context comprises a global object together with a set of build-in objects and function mrnnotx .

The optional argument i i S n b x will be shallow-copied to seed the initial contents of the global object use ntado by the context.

,[

])

c e t S r p compiles c d but does not run it. Instead, it returns a v . c i t object representing this raecit oe mSrp

compiled code. This script can be run later many times using methods below. The returned script is not bound any global object. It is bound before each run, just for that run. f l n m is optional, it's only used in stack ieae traces. In case of syntax error in c d , c e t S r p prints the syntax error to stderr and throws an exception. oe raecit

:S

A class for running scripts. Returned by vm.createScript.

I T

()

Similar to v . u I T i C n e t but a method of a precompiled S r p object. s r p . u I T i C n e t mrnnhsotx cit citrnnhsotx access to the g o a object (v8: in actual context). lbl Example of using s r p . u I T i C n e t to compile code once and run it multiple times: citrnnhsotx
vrveur(v' am=rqie'm) goaVr=0 lbla vrsrpmcetSrp(goaVr+'mfl.m) acit=v.raecit'lbla=1,'yiev' fr(ai<10=1 ovri=000i+){ srp.uITiCnet) citrnnhsotx( } cnoelggoaVr osl.o(lbla) /00 /10

runs the code of s r p and returns the result. Running code does not have access to local scope, but does ha cit

I N

([

])

Similar to v . u I N w o t x a method of a precompiled S r p object. s r p . u I N w o t x mrnneCnet cit citrnneCnet the code of s r p with s n b x as the global object and returns the result. Running code does not have cit ado access to local scope. s n b x is optional. ado

nodej .o g/api/all.h ml

137/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Example: compile code that increments a global variable and sets one, then execute this code multiple times. These globals are contained in the sandbox.
vruieur(ui', atl=rqie'tl) veur(v', m=rqie'm) snbx={ ado aia:'a' nmlct, cut on:2 } vrsrpmcetSrp(cut+nmkty'mfl.m) acit=v.raecit'on=1ae="it",'yiev' fr(ai<1=1 ovri=00i+){ srp.uINwotx(ado) citrnneCnetsnbx } cnoelgui.npc(ado) osl.o(tlisetsnbx) /nmlct,cut2aekty /{aia:'a'on:1,nm:'it'}

Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, s r p . u I N w o t x is quite useful, but safely running untrusted code requires a separate citrnneCnet process.

P
Saiiytbe tblt:3Sal

Node provides a tri-directional p p n 3 facility through the c i d p o e s module. oe() hl_rcs It is possible to stream data through a child's s d n, s d u , and s d r in a fully non-blocking way. ti tot ter

To create a child process use r q i e ' h l _ r c s ' . p w ( or r q i e ' h l _ r c s ' . o k ) eur(cidpoes)san) eur(cidpoes)fr( The semantics of each are slightly different, and explained below.

:C

C i d r c s is an E e t m t e . hlPoes vnEitr

Child processes always have three streams associated with them. c i d s d n, c i d s d u , and hl.ti hl.tot
c i d s d r . These may be shared with the stdio streams of the parent process, or they may be separate hl.ter

stream objects which can be piped to and from.

The ChildProcess class is not intended to be used directly. Use the s a n ) or f r ( methods to create a Ch pw( ok) Process instance.

nodej .o g/api/all.h ml

138/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

:'

'

c d Number the exit code, if it exited normally. oe s g a String the signal passed to kill the child process, if it was killed by the parent. inl

This event is emitted after the child process ends. If the process terminated normally, c d is the final exit cod oe of the process, otherwise n l . If the process terminated due to receipt of a signal, s g a is the string name ul inl the signal, otherwise n l . ul See w i p d 2 . ati()

.
Stream object

A W i a l t e m that represents the child process's s d n. Closing this stream via e d ) often causes the rtbeSra ti n( child process to terminate. If the child stdio streams are shared with the parent, then this will not be set.

.
Stream object A R a a l t e m that represents the child process's s d u . edbeSra tot If the child stdio streams are shared with the parent, then this will not be set.

.
Stream object A R a a l t e m that represents the child process's s d r . edbeSra ter If the child stdio streams are shared with the parent, then this will not be set.

.
Integer The PID of the child process. Example:
vrsan=rqie'hl_rcs'.pw, apweur(cidpoes)san ge=san'rp,[sh] rppw(ge''s')

nodej .o g/api/all.h ml

139/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

cnoelg'pwehli:'+ge.i) osl.o(Sandcidpdrppd ge.ti.n( rpsdned)

([

])

s g a String inl

Send a signal to the child process. If no argument is given, the process will be sent ' I T R '. See s g a ( ) SGEM inl7 for a list of available signals.
vrsan=rqie'hl_rcs'.pw, apweur(cidpoes)san ge=san'rp,[sh] rppw(ge''s') ge.n'xt,fntocd,sga){ rpo(ei'ucin(oeinl cnoelg'hlrcsemntddeteepfsga+inl osl.o(cidpoestriaeuorcitoinl'sga) } ) /edSGUopoes /snIHPtrcs ge.il'IHP) rpkl(SGU'

Note that while the function is called k l , the signal delivered to the child process may not actually kill it. il
k l really just sends a signal to a process. il

See k l ( ) il2

,[

])

m s a eObject esg s n H n l Handle object edade

Send a message (and, optionally, a handle object) to a child process. See c i d p o e s f r ( for details. hl_rcs.ok)

_
o t o sObject pin

,[

],[

])

c m a dString The command to run omn a g Array List of string arguments rs c dString Current working directory of the child process w c s o F sArray Deprecated File descriptors for the child to use for stdio. (See below) utmd e vObject Environment key-value pairs n s t i Boolean esd

return: ChildProcess object Launches a new process with the given c m a d, with command line arguments in a g . If omitted, a g omn rs rs defaults to an empty Array.

nodej .o g/api/all.h ml

140/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

The third argument is used to specify additional options, which defaults to:
{cdneie, w:udfnd evrcs.n n:poesev }

c d allows you to specify the working directory from which the process is spawned. Use e v to specify w n

environment variables that will be visible to the new process. Example of running l l u r, capturing s d u , s d r , and the exit code: sh/s tot ter
vrui=rqie'tl) atleur(ui', san=rqie'hl_rcs'.pw, pweur(cidpoes)san l=san's,[h,'ur] spw(l''l'/s') l.toto(dt'ucin(aa ssdu.n'aa,fntodt){ cnoelg'totaa osl.o(sdu:'+dt) } ) l.tero(dt'ucin(aa ssdr.n'aa,fntodt){ cnoelg'teraa osl.o(sdr:'+dt) } ) l.n'xt,fntocd){ so(ei'ucin(oe cnoelg'hlrcsxtdwtoe'+cd) osl.o(cidpoeseieihcdoe } )

Example: A very elaborate way to run 'ps ax | grep ssh'


vrui=rqie'tl) atleur(ui', san=rqie'hl_rcs'.pw, pweur(cidpoes)san p=san's,[a') spw(p''x], ge=san'rp,[sh] rppw(ge''s') p.toto(dt'ucin(aa ssdu.n'aa,fntodt){ ge.ti.rt(aa rpsdnwiedt) } ) p.tero(dt'ucin(aa ssdr.n'aa,fntodt){ cnoelg'ssdr:'+dt) osl.o(pteraa } ) p.n'xt,fntocd){ so(ei'ucin(oe icd=){ f(oe!=0 cnoelg'spoeseieihcdoe osl.o(prcsxtdwtoe'+cd) } ge.ti.n( rpsdned) } ) ge.toto(dt'ucin(aa rpsdu.n'aa,fntodt){ cnoelgdt) osl.o(aa

nodej .o g/api/all.h ml

141/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

} ) ge.tero(dt'ucin(aa rpsdr.n'aa,fntodt){ cnoelg'rpsdr:'+dt) osl.o(geteraa } ) ge.n'xt,fntocd){ rpo(ei'ucin(oe icd=){ f(oe!=0 cnoelg'rppoeseieihcdoe osl.o(gercsxtdwtoe'+cd) } } )

Example of checking for failed exec:


vrsan=rqie'hl_rcs'.pw, apweur(cidpoes)san cid=san'a_omn' hlpw(bdcmad) cidsdr.eEcdn(uf' hl.terstnoig't8) cidsdr.n'aa,fntodt){ hl.tero(dt'ucin(aa i/eev\\/ts(aa){ f(^xcp().etdt) cnoelg'aldttrhlrcs.) osl.o(Fieosatcidpoes' } } )

Note that if spawn receives an empty options object, it will result in spawning the process with an empty environment rather than using p o e s e v. This due to backwards compatibility issues with a deprecated AP rcs.n

There is a deprecated option called c s o F s which allows one to specify specific file descriptors for the stdio utmd of the child process. This API was not portable to all platforms and therefore removed. With c s o F s utmd possible to hook up the new process' [ t i , s d u , s d r ] to existing streams; meant that a new sdntotter 1 stream should be created. Use at your own risk. There are several internal options. In particular s d n t e m, s d u S r a , s d r S r a . They are for tiSra tottem tertem INTERNAL USE ONLY. As with all undocumented APIs in Node, they should not be used. See also: c i d p o e s e e ( and c i d p o e s f r ( hl_rcs.xc) hl_rcs.ok)

_
o t o sObject pin

,[

],

c m a dString The command to run, with space-separated arguments omn c dString Current working directory of the child process w c s o F sArray Deprecated File descriptors for the child to use for stdio. (See below) utmd e vObject Environment key-value pairs n s t i Boolean esd e c d n String (Default: 'utf8') noig t m o tNumber (Default: 0) ieu m x u f rNumber (Default: 200*1024) aBfe k l S g a String (Default: 'SIGTERM') ilinl

nodej .o g/api/all.h ml

142/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

c l b c Function called with the output when process terminates alak c d Integer Exit code oe s d u Buffer tot s d r Buffer ter

Return: ChildProcess object Runs a command in a shell and buffers the output.
vruieur(ui', atl=rqie'tl) eeeur(cidpoes)ee, xc=rqie'hl_rcs'.xc cid hl cid=ee(ct*ja_ie|wl, hlxc'a.sbdflc' fntoerrtotter ucin(ro,sdu,sdr){ cnoelg'tottot osl.o(sdu:'+sdu) cnoelg'terter osl.o(sdr:'+sdr) ierr!=nl){ f(ro=ul cnoelg'xcerrro) osl.o(eero:'+err } } )

The callback gets the arguments ( r o , s d u , s d r ). On success, e r r will be n l . On error, errtotter ro ul will be an instance of E r r and e r c d will be the exit code of the child process, and e r s g a will be ro r.oe r.inl set to the signal that terminated the process. There is a second optional argument to specify several options. The default options are
{ecdn:'t8, noiguf' tmot, ieu:0 mxufr0*04 aBfe:2012, klSga:'ITR' ilinlSGEM, cdul w:nl, evul} n:nl

If t m o t is greater than 0, then it will kill the child process if it runs longer than t m o t milliseconds. The ieu ieu allowed on stdout or stderr - if this value is exceeded then the child process is killed.

child process is killed with k l S g a (default: ' I T R '). m x u f r specifies the largest amount of data ilinl SGEM aBfe

_
o t o sObject pin

F (

f l String The filename of the program to run ie a g Array List of string arguments rs c dString Current working directory of the child process w c s o F sArray Deprecated File descriptors for the child to use for stdio. (See below) utmd e vObject Environment key-value pairs n s t i Boolean esd e c d n String (Default: 'utf8') noig t m o tNumber (Default: 0) ieu

nodej .o g/api/all.h ml

143/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

m x u f rNumber (Default: 200*1024) aBfe k l S g a String (Default: 'SIGTERM') ilinl c l b c Function called with the output when process terminates alak c d Integer Exit code oe s d u Buffer tot s d r Buffer ter

Return: ChildProcess object This is similar to c i d p o e s e e ( except it does not execute a subshell but rather the specified file hl_rcs.xc) directly. This makes it slightly leaner than c i d p o e s e e . It has the same options. hl_rcs.xc

_
o t o sObject pin

,[

],[

])

m d l P t String The module to run in the child oueah a g Array List of string arguments rs c dString Current working directory of the child process w c s o F sArray Deprecated File descriptors for the child to use for stdio. (See below) utmd e vObject Environment key-value pairs n s t i Boolean esd e c d n String (Default: 'utf8') noig t m o tNumber (Default: 0) ieu c l b c Function called with the output when process terminates alak c d Integer Exit code oe s d u Buffer tot s d r Buffer ter

Return: ChildProcess object This is a special case of the s a n ) functionality for spawning Node processes. In addition to having all the pw(

methods in a normal ChildProcess instance, the returned object has a communication channel built-in. The channel is written to with c i d s n ( e s g , [ e d a d e ) and messages are received by a ' e s g ' hl.edmsaesnHnl] msae event on the child. For example:
vrceur(cidpoes) ap=rqie'hl_rcs' vrn=c.ok_drae+'sbj' apfr(_inm/u.s) no(msae,fnto(){ .n'esg'ucinm cnoelg'AETgtmsae') osl.o(PRNoesg:,m } ) nsn(el:'ol'} .ed{hlowrd)

And then the child script, ' u . s might look like this: sbj'
poeso(msae,fnto(){ rcs.n'esg'ucinm cnoelg'HLoesg:,m osl.o(CIDgtmsae')

nodej .o g/api/all.h ml

144/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

} ) poessn(o:'a'} rcs.ed{fobr)

In the child the p o e s object will have a s n ( method, and p o e s will emit objects each time it receive rcs ed) rcs a message on its channel. By default the spawned Node process will have the stdin, stdout, stderr associated with the parent's.

These child Nodes are still whole new instances of V8. Assume at least 30ms startup and 10mb memory for each new Node. That is, you cannot create many thousands of them. The s n H n l option to c i d s n ( is for sending a handle object to another process. Child will receive edade hl.ed) the handle as as second argument to the m s a e event. Here is an example of sending a handle: esg
vrsreeur(nt)cetSre( aevr=rqie'e'.raeevr) vrcid=rqie'hl_rcs'.ok_drae+'cidj' ahleur(cidpoes)fr(_inm/hl.s) /pnuhevrojcnedtehnl. /Oeptesrebetadsnhade sre.itn13,fnto( evrlse(37ucin){ cidsn(evrre}evr_ade hl.ed{sre:tu,sre.hnl) } )

Here is an example of receiving the server handle and sharing it between processes:
poeso(msae,fnto(,sreHnl){ rcs.n'esg'ucinmevrade isreHnl){ f(evrade vrsreeur(nt)cetSre( aevr=rqie'e'.raeevr) sre.itnsreHnl) evrlse(evrade } } )

A
Saiiyokd tblt:5Lce

This module is used for writing unit tests for your applications, you can access it with r q i e ' s e t ) eur(asr'

Throws an exception that displays the values for a t a and e p c e separated by the provided operator. cul xetd

),

,[

])

Tests if value is a t u value, it is equivalent to a s r . q a ( r e a u , m s a e re seteultu,vleesg)

nodej .o g/api/all.h ml

145/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

,[

])

Tests shallow, coercive equality with the equal comparison operator ( = ). =

,[

])

Tests shallow, coercive non-equality with the not equal comparison operator ( ! ). =

,[

])

Tests for deep equality.

,[

])

Tests for any deep inequality.

,[

])

Tests strict equality, as determined by the strict equality operator ( = = ) =

,[

])

Tests strict non-equality, as determined by the strict not equal operator ( ! = ) =

,[

],[

])

Expects b o k to throw an error. e r r can be constructor, regexp or validation function. lc ro Validate instanceof using constructor:
asr.hos settrw( fnto( ucin){ trwnwErr"rnau" hoero(Wogvle) } , Err ro )

Validate error message using RegExp:


asr.hos settrw( fnto( ucin){ trwnwErr"rnau" hoero(Wogvle) } , /au/ vle )

Custom error validation:

nodej .o g/api/all.h ml

146/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

asr.hos settrw( fnto( ucin){ trwnwErr"rnau" hoero(Wogvle) } , fnto(r){ uciner ierisacoro)&vle.eter f((rntnefErr&/au/ts(r)){ rtrre euntu } } , "nxetderr uepcero" )

N T

,[

],[

])

Expects b o k not to throw an error, see assert.throws for details. lc

. E
callbacks.

Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, e r r ro

TTY
Saiiytbe tblt:3Sal

Use r q i e ' t ' to access this module. eur(ty) Example:


vrty=rqie't' ateur(ty) poessdnrsm( rcs.ti.eue) tystaMd(re t.eRwoetu) poessdno(kyrs'ucinca,ky rcs.ti.n'epes,fnto(hre){ iky&e.tl&e.ae=c){ f(e&kycr&kynm='' cnoelg'rcflei' osl.o(gaeuxt) poesei( rcs.xt) } } )

( )

Returns t u or f l e depending on if the f is associated with a terminal. re as d

nodej .o g/api/all.h ml

147/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

m d should be t u or f l e This sets the properties of the current process's stdin fd to act either as a raw oe re as .

device or default.

Z
Saiiytbe tblt:3Sal

You can access this module with:


vrzieur(zi' alb=rqie'lb)

This provides bindings to Gzip/Gunzip, Deflate/Inflate, and DeflateRaw/InflateRaw classes. Each class takes th same options, and is a readable/writable Stream.

E
Compressing or decompressing a file can be done by piping an fs.ReadStream into a zlib stream, then into an fs.WriteStream.
vrgilbcetGi( azp=zi.raezp) vrfeur(f' as=rqie's) vrip=f.raeedtem'nu.x' anscetRaSra(ipttt) vrot=f.raertSra(iptttg' auscetWietem'nu.x.z) ippp(zp.ieot n.iegi)pp(u)

Compressing or decompressing data in one step can be done by using the convenience methods.
vript='................' anu................. zi.elt(nu,fnto(r,bfe){ lbdfaeiptucinerufr i!r){ f(er cnoelgbfe.otig'ae4) osl.o(ufrtSrn(bs6') } } ) vrbfeeufr'JTyAGve=,'ae4) aufr=nwBfe(ez0MATB8'bs6' zi.ni(ufrucinerufr lbuzpbfe,fnto(r,bfe){ i!r){ f(er cnoelgbfe.otig) osl.o(ufrtSrn() } } )

To use this module in an HTTP client or server, use the accept-encoding on requests, and the content-encoding header on responses. Note: these e amples are drasticall simplified to sho the basic concept. Zlib encoding can be expensive, the results ought to be cached. See Memory Usage Tuning below for more information on the

nodej .o g/api/all.h ml

148/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

speed/memory/compression tradeoffs involved in zlib usage.


/letrqeteape /cineusxml vrzieur(zi' alb=rqie'lb) vrhteur(ht' atp=rqie'tp) vrfeur(f' as=rqie's) vrrqet=ht.e(otism' aeustpgt{hs:'z.e, ah/, pt:'' ot0 pr:8, edr:{'cetecdn'gi,elt'}} haesacpnoig:'zpdfae) rqeto(rsos'ucinrsos){ eus.n'epne,fnto(epne vrotuscetWietem'z.eidxhm' aupt=f.raertSra(ism_ne.tl) sicrsos.edr[cnetecdn'){ wth(epnehaes'otnnoig] /rutuezi.raeni(ohnlohcss /o,jsslbcetUzp)tadebtae csgi' ae'zp: rsos.iezi.raeuzp).ieotu) epnepp(lbcetGni()pp(upt bek ra csdfae: ae'elt' rsos.iezi.raenlt()pp(upt epnepp(lbcetIfae).ieotu) bek ra dfut eal: rsos.ieotu) epnepp(upt bek ra } } ) /evreape /srexml /unnzpoeainovreussqieepnie /Rnigagiprtoneeyrqetiutxesv. /twudbuhmrfiinoccetecmrseufr /Iolemcoeefcettahhopesdbfe. vrzieur(zi' alb=rqie'lb) vrhteur(ht' atp=rqie'tp) vrfeur(f' as=rqie's) ht.raeevrfnto(eus,rsos){ tpcetSre(ucinrqetepne vrrw=f.raeedtem'ne.tl) aascetRaSra(idxhm' vracpEcdneus.edr[acpnoig] acetnoig=rqethaes'cetecdn' i!cetnoig f(acpEcdn){ acpEcdn' cetnoig=' } /oehsioofratacpnoigpre. /Nt:tisntacnomncetecdnasr /etp/www.r/rtcl/f21/f21e1.tlsc43 /Seht:/w.3ogPooosrc66rc66sc4hm#e1. iacpEcdn.ac(\dfaeb) f(cetnoigmth/belt\/){ rsos.rtHa(0,{'otnnoig:'elt'} epnewieed20cnetecdn'dfae) rwpp(lbcetDfae).iersos) a.iezi.raeelt()pp(epne }esf(cetnoigmth/bzpb) leiacpEcdn.ac(\gi\/){ rsos.rtHa(0,{'otnnoig:'zp) epnewieed20cnetecdn'gi'} rwpp(lbcetGi()pp(epne a.iezi.raezp).iersos) }es le{ rsos.rtHa(0,{) epnewieed20} rwpp(epne a.iersos) } }.itn13) )lse(37

nodej .o g/api/all.h ml

149/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

C
the zlib documentation. See http://zlib.net/manual.html#Constants for more details.

All of the constants defined in zlib.h are also defined on r q i e ' l b ). They are described in more detail i eur(zi'

([

])

Returns a new Gzip object with an options.

([

])

Returns a new Gunzip object with an options.

([

])

Returns a new Deflate object with an options.

([

])

Returns a new Inflate object with an options.

([

])

Returns a new DeflateRaw object with an options.

([

])

Returns a new InflateRaw object with an options.

([

])

Returns a new Unzip object with an options.

.G

Compress data using gzip.

.G

Decompress a gzip stream.

.D

Compress data using deflate.

nodej .o g/api/all.h ml

150/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

.I

Decompress a deflate stream.

.D

Compress data using deflate, and do not append a zlib header.

.I

Decompress a raw deflate stream.

.U

Decompress either a Gzip- or Deflate-compressed stream by auto-detecting the header.

All of these take a string or buffer as the first argument, and call the supplied callback with c l b c ( r o , alakerr
r s l ) The compression/decompression engine is created using the default settings in all convenience eut .

methods. To supply different options, use the zlib classes directly.

Compress a string with Deflate.

Compress a string with DeflateRaw.

Compress a string with Gzip.

Decompress a raw Buffer with Gunzip.

Decompress a raw Buffer with Inflate.

Decompress a raw Buffer with InflateRaw.

nodej .o g/api/all.h ml

151/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Decompress a raw Buffer with Unzip.

O
Each class takes an options object. All options are optional. (The convenience methods use the default settings for all options.) Note that some options are only relevant when compressing, and are ignored by the decompression classes. chunkSize (default: 16*1024) windowBits level (compression only) memLevel (compression only) strategy (compression only) See the description of d f a e n t and i f a e n t at eltIi2 nltIi2 http://zlib.net/manual.html#Advanced for more information on these.

From z i / c n . , modified to node's usage: lbzofh The memory requirements for deflate are (in bytes):
(<(idwis2)+1<mmee+) 1<wnoBt+)(<(eLvl9)

that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) plus a few kilobytes for small objects. For example, if you want to reduce the default memory requirements from 256K to 128K, set the options to:
{wnoBt:1,mmee:7} idwis4eLvl

Of course this will generally degrade compression (there's no free lunch). The memory requirements for inflate are (in bytes)
1<idwis <wnoBt

that is, 32K for windowBits=15 (default value) plus a few kilobytes for small objects. This is in addition to a single internal output slab buffer of size c u k i e, which defaults to 16K. hnSz The speed of zlib compression is affected most dramatically by the l v l setting. A higher level will result in ee

better compression, but will take longer to complete. A lower level will result in less compression, but will be mu faster.

nodej .o g/api/all.h ml

152/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

In general, greater memory usage options will mean that node has to make fewer calls to zlib, since it'll be able process more data in a single w i e operation. So, this is another factor that affects the speed, at the cost of rt memory usage.

SaiiyPrzn tblt:4AIFoe

Provides a few basic operating-system related utility functions. Use r q i e ' s ) to access this module. eur(o'

()

Returns the hostname of the operating system.

()

Returns the operating system name.

()

Returns the operating system platform.

()

Returns the operating system CPU architecture.

()

Returns the operating system release.

()

Returns the system uptime in seconds.

()

Returns an array containing the 1, 5, and 15 minute load averages.

()

Returns the total amount of system memory in bytes.

nodej .o g/api/all.h ml

153/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

()

Returns the amount of free system memory in bytes.

()

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). Example inspection of os.cpus:
[{mdlItlRoeT)iP6@28Gz, oe:'ne()Cr(M7CU80.0H' sed96 pe:22, tms ie: sr500 {ue:222, ie, nc:0 y:330 ss04, de00580 il:17367, r:0}} iq, {mdlItlRoeT)iP6@28Gz, oe:'ne()Cr(M7CU80.0H' sed96 pe:22, tms ie: sr090 {ue:366, ie, nc:0 y:290 ss68, de01600 il:17598, r:0}} iq, {mdlItlRoeT)iP6@28Gz, oe:'ne()Cr(M7CU80.0H' sed96 pe:22, tms ie: sr440 {ue:285, ie, nc:0 y:270 ss15, de00130 il:17997, r:0}} iq, {mdlItlRoeT)iP6@28Gz, oe:'ne()Cr(M7CU80.0H' sed96 pe:22, tms ie: sr580 {ue:268, ie, nc:0 y:140 ss93, de00040 il:17958, r:2, iq0}} {mdlItlRoeT)iP6@28Gz, oe:'ne()Cr(M7CU80.0H' sed96 pe:22, tms ie: sr150 {ue:518, ie0 nc:2, y:490 ss00, de00450 il:17821, r:0}} iq, {mdlItlRoeT)iP6@28Gz, oe:'ne()Cr(M7CU80.0H'

nodej .o g/api/all.h ml

154/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

sed96 pe:22, tms ie: sr960 {ue:216, ie, nc:0 y:330 ss46, de00800 il:17880, r:1, iq0}} {mdlItlRoeT)iP6@28Gz, oe:'ne()Cr(M7CU80.0H' sed96 pe:22, tms ie: sr020 {ue:386, ie, nc:0 y:540 ss51, de01290 il:17197, r:80}} iq8, {mdlItlRoeT)iP6@28Gz, oe:'ne()Cr(M7CU80.0H' sed96 pe:22, tms ie: sr640 {ue:265, ie40 nc:18, y:390 ss42, de02700 il:17521, r:3 iq0}}]

()

Get a list of network interfaces:


{l0 o: drs:':'aiyIv'nenlre} [{ades:1,fml:'P6,itra:tu, drs:'e0:'aiyIv'nenlre} {adesf8:1,fml:'P6,itra:tu, drs:'2...'aiyIv'nenlre}] {ades17001,fml:'P4,itra:tu, e1 n: drs:'e0:accf:eff9'aiyIv' [{adesf8:cb:8ffe:96,fml:'P6, nenlas, itra:fle} drs:'00113,fml:'P4,itra:fle}] {ades1...2'aiyIv'nenlas, vnt:[{ades1.99.5'aiyIv'nenlas, me1drs:'09.924,fml:'P4,itra:fle}] vnt:[{ades1.88.'aiyIv'nenlas, me8drs:'08.81,fml:'P4,itra:fle}] pp:[{ades1...3'aiyIv'nenlas p0drs:'02021,fml:'P4,itra:fle}]}

D
Saiiytbe tblt:3Sal

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 d b g argument; a prompt will appear: eu

nodej .o g/api/all.h ml

155/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

%ndeuycitj oedbgmsrp.s <dbgeitnnnpr88 eugrlseigoot55 cnetn..o oncig.k bekihm/nun/oegtidtymsrp.s1 ran/oeidtyCd/i/nun/ycitj: 1x=5 2stieu(ucin( eTmotfnto){ 3dbge eugr dbg eu>

Node's debugger client doesn't support the full range of commands, but simple step and inspection is possible. By putting the statement d b g e into the source code of your script, you will enable a breakpoint. eugr For example, suppose m s r p . s looked like this: ycitj
/ycitj /msrp.s x=5 stieu(ucin( eTmotfnto){ dbge eugr cnoelg"ol" osl.o(wrd) }00 ,10) cnoelg"el" osl.o(hlo)

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


%ndeuycitj oedbgmsrp.s <dbgeitnnnpr88 eugrlseigoot55 cnetn..o oncig.k bekihm/nun/oegtidtymsrp.s1 ran/oeidtyCd/i/nun/ycitj: 1x=5 2stieu(ucin( eTmotfnto){ 3dbge eugr dbgot eu>cn <hlo el bekihm/nun/oegtidtymsrp.s3 ran/oeidtyCd/i/nun/ycitj: 1x=5 2stieu(ucin( eTmotfnto){ 3dbge eugr 4cnoelg"ol" osl.o(wrd) 5}00 ,10) dbget eu>nx bekihm/nun/oegtidtymsrp.s4 ran/oeidtyCd/i/nun/ycitj: 2stieu(ucin( eTmotfnto){ 3dbge eugr 4cnoelg"ol" osl.o(wrd) 5}00 ,10) 6cnoelg"el" osl.o(hlo) dbgel eu>rp PesCrolaedbgrp rstl+Cteveuel >x 5 >22 +

nodej .o g/api/all.h ml

156/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

4 dbget eu>nx <wrd ol bekihm/nun/oegtidtymsrp.s5 ran/oeidtyCd/i/nun/ycitj: 3dbge eugr 4cnoelg"ol" osl.o(wrd) 5}00 ,10) 6cnoelg"el" osl.o(hlo) 7 dbgut eu>qi %

The r p command allows you to evaluate code remotely. The n x command steps over to the next line. The el et are a few other commands available and more to come. Type h l to see others. ep

You can watch expression and variable values while debugging your code. On every breakpoint each expression from the watchers list will be evaluated in the current context and displayed just before the breakpoint's source code listing. To start watching an expression, type w t h " y e p e s o " . w t h r prints the active watchers. To ac(m_xrsin) aces remove a watcher, type u w t h " y e p e s o " . nac(m_xrsin)

C
S

c n , c- Continue execution ot n x , n- Step next et s e , s- Step in tp o t o- Step out u,

B
s t r a p i t ) s ( - Set breakpoint on current line eBekon(, b) s t r a p i t ' n ) ) s ( . )- Set breakpoint on a first statement in functions body eBekon(f(', b.. s t r a p i t ' c i t j ' ) s ( . )- Set breakpoint on first line of script.js eBekon(srp.s,1, b.. c e r r a p i t c ( . )- Clear breakpoint laBekon, b..

I
b c t a e b - Print backtrace of current execution frame akrc, t l s ( )- List scripts source code with 5 line context (5 lines before and after) it5 w t h e p )- Add expression to watch list ac(xr u w t h e p )- Remove expression from watch list nac(xr

nodej .o g/api/all.h ml

157/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

w t h r - List all watchers and their values (automatically listed on each breakpoint) aces r p - Open debugger's repl for evaluation in debugging script's context el

r n- Run script (automatically runs on debugger's start) u r s a t- Restart script etr k l - Kill script il

V
s r p s- List all loaded scripts cit v r i n- Display v8's version eso

The V8 debugger can be enabled and accessed either by starting Node with the d b g command-line flag or eu by signaling an existing Node process with S G S 1. IUR

C
SaiiyxeietlDatccagsiuuevrin tblt:1Eprmnarsihnenftresos

A single instance of Node runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node processes to handle the load. The cluster module allows you to easily create a network of processes that all share server ports.
vrcutr=rqie'lse' alseeur(cutr) vrhteur(ht' atp=rqie'tp) vrnmPs=rqie's)cu(.egh auCUeur(o'.ps)lnt icutriMse){ f(lse.satr /okwres /Frokr. fr(ai<nmPs+){ ovri=0uCUi+ cutrfr( lse.ok) } cutro(dah,fnto(okr lse.n'et'ucinwre){ cnoelg'okr'+wre.iid) osl.o(wreokrpd+'de' } ) }es le{ /okrpoesshvtpsre. /Wrercseaeahtevr ht.evrfnto(e,rs tpSre(ucinrqe){ rswieed20 e.rtHa(0) rsed"elol\" e.n(hlowrdn)

nodej .o g/api/all.h ml

158/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

}.itn80) )lse(00 }

Running node will now share port 8000 between the workers:
%ndevrj oesre.s Wre48oln okr23nie Wre47oln okr23nie

The difference between c u t r f r ( and c i d p o e s f r ( is simply that cluster allows TCP server lse.ok) hl_rcs.ok) to be shared between workers. c u t r f r is implemented on top of c i d p o e s f r . The message lse.ok hl_rcs.ok is a cluster which keeps count of the number of requests in the master process via message passing:
vrcutr=rqie'lse' alseeur(cutr) vrhteur(ht' atp=rqie'tp) vrnmes=0 auRq icutriMse){ f(lse.satr /okwres /Frokr. fr(ai<2+){ ovri=0i+ vrwrelse.ok) aokr=cutrfr( wre.n'esg'ucinmg okro(msae,fnto(s){ imgcd&s.m='oiyeus' f(s.m&mgcd=ntfRqet){ nmes+ uRq+ } } ) } stnevlfnto( eItra(ucin){ cnoelg"uRq"uRq) osl.o(nmes=,nmes }00 ,10) }es le{ /okrpoesshvtpsre. /Wrercseaeahtevr ht.evrfnto(e,rs tpSre(ucinrqe){ rswieed20 e.rtHa(0) rsed"elol\" e.n(hlowrdn) /edmsaetatrpoes /Snesgomsercs poessn(m:'oiyeus'} rcs.ed{cdntfRqet) }.itn80) )lse(00 }

passing API that is available with c i d p o e s f r is available with c u t r as well. As an example, her hl_rcs.ok lse

()

Spawn a new worker process. This can only be called from the master process.

. M

nodej .o g/api/all.h ml

159/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

. W
Boolean flags to determine if the current process is a master or a worker process in a cluster. A process i M s e if p o e s e v N D _ O K R I is undefined. satr rcs.n.OEWRE_D

:'

'

When any of the workers die the cluster module will emit the 'death' event. This can be used to restart the work by calling f r ( again. ok)
cutro(dah,fnto(okr lse.n'et'ucinwre){ cnoelg'okr'+wre.iidetr..) osl.o(wreokrpd+'de.rsat.' cutrfr( lse.ok) } )

Different techniques can be used to restart the worker depending on the application.

1T

There are many third party modules for Node. At the time of writing, August 2010, the master repository of modules is the wiki page.

This appendix is intended as a SMALL guide to new-comers to help them quickly find what are considered to b quality modules. It is not intended to be a complete list. There may be better more complete modules found elsewhere. Module Installer: npm HTTP Middleware: Connect Web Framework: Express Web Sockets: Socket.IO HTML Parsing: HTML5 mDNS/Zeroconf/Bonjour RabbitMQ, AMQP mysql Serialization: msgpack Scraping: Apricot Debugger: ndb is a CLI debugger inspector is a web based tool. pcap binding ncurses Testing/TDD/BDD: vows, mocha, mjsunit.runner Patches to this list are welcome.

nodej .o g/api/all.h ml

160/161

3/31/12

Abo

hi Doc men a ion Node.j

0.6.14 Man al & Doc men a ion

Node.js

Download

About

npm Registry

Docs

Blog

Community

Logos

Jobs

@nodejs

Copyright Joyent, Inc, Node.js is a trademark of Joyent, Inc. View license.

o1.32. Vimi mha been pda ed o

nodej .o g/api/all.h ml

161/161

Você também pode gostar