Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
4535 lines (3017 sloc) 196 KB
<!DOCTYPE html>
<title>all - Node.js Manual &amp; Documentation</title>
<link type="image/x-icon" rel="icon" href="/favicon.ico" />
<link type="image/x-icon" rel="shortcut icon" href="/favicon.ico" />
<link rel="stylesheet" href="assets/style.css" type="text/css" media="all" />
<link rel="stylesheet" href="assets/sh.css" type="text/css" media="all"/>
<div id="container">
<h1>Node.js Manual &amp; Documentation</h1>
<div id="gtoc">
<p><a href="index.html">Index</a> | <a href="all.html">View on single page</a></p>
<hr />
<div id="toc"><h2>Table Of Contents</h2><ul><li><a href="#synopsis">Synopsis</a></li><li><a href="#global_Objects">Global Objects</a><ul><li><a href="#global">global</a></li><li><a href="#process">process</a></li><li><a href="#console">console</a></li><li><a href="#require">require()</a></li><li><a href="#require.resolve">require.resolve()</a></li><li><a href="#require.cache">require.cache</a></li><li><a href="#require.paths">require.paths</a></li><li><a href="#__filename">__filename</a></li><li><a href="#__dirname">__dirname</a></li><li><a href="#module">module</a></li><li><a href="#exports">exports</a></li><li><a href="#setTimeout">setTimeout(cb, ms)</a></li><li><a href="#clearTimeout">clearTimeout(t)</a></li><li><a href="#setInterval">setInterval(cb, ms)</a></li><li><a href="#clearInterval">clearInterval(t)</a></li></ul></li><li><a href="#console">console</a><ul><li><a href="#console.log">console.log()</a></li><li><a href=""></a></li><li><a href="#console.warn">console.warn()</a></li><li><a href="#console.error">console.error()</a></li><li><a href="#console.dir">console.dir(obj)</a></li><li><a href="#console.time">console.time(label)</a></li><li><a href="#console.timeEnd">console.timeEnd(label)</a></li><li><a href="#console.trace">console.trace()</a></li><li><a href="#console.assert">console.assert()</a></li></ul></li><li><a href="#timers">Timers</a><ul><li><a href="#setTimeout">setTimeout(callback, delay, [arg], [...])</a></li><li><a href="#clearTimeout">clearTimeout(timeoutId)</a></li><li><a href="#setInterval">setInterval(callback, delay, [arg], [...])</a></li><li><a href="#clearInterval">clearInterval(intervalId)</a></li></ul></li><li><a href="#modules">Modules</a><ul><li><a href="#core_Modules">Core Modules</a></li><li><a href="#file_Modules">File Modules</a></li><li><a href="#loading_from_node_modules_Folders">Loading from `node_modules` Folders</a></li><li><a href="#folders_as_Modules">Folders as Modules</a></li><li><a href="#caching">Caching</a><ul><li><a href="#module_Caching_Caveats">Module Caching Caveats</a></li></ul></li><li><a href="#module.exports">module.exports</a></li><li><a href="#all_Together...">All Together...</a></li><li><a href="#loading_from_the_require.paths_Folders">Loading from the `require.paths` Folders</a><ul><li><a href="#note_Please_Avoid_Modifying_require.paths_">Note:** Please Avoid Modifying `require.paths`</a><ul><li><a href="#setting_require.paths_to_some_other_value_does_nothing.">Setting `require.paths` to some other value does nothing.</a></li><li><a href="#putting_relative_paths_in_require.paths_is..._weird.">Putting relative paths in `require.paths` is... weird.</a></li><li><a href="#zero_Isolation">Zero Isolation</a></li></ul></li></ul></li><li><a href="#accessing_the_main_module">Accessing the main module</a></li></ul></li><li><a href="#addenda_Package_Manager_Tips">Addenda: Package Manager Tips</a></li><li><a href="#addons">Addons</a></li><li><a href="#process">process</a><ul><li><a href="#event_exit_">Event: 'exit'</a></li><li><a href="#event_uncaughtException_">Event: 'uncaughtException'</a></li><li><a href="#signal_Events">Signal Events</a></li><li><a href="#process.stdout">process.stdout</a></li><li><a href="#process.stderr">process.stderr</a></li><li><a href="#process.stdin">process.stdin</a></li><li><a href="#process.argv">process.argv</a></li><li><a href="#process.execPath">process.execPath</a></li><li><a href="#process.chdir">process.chdir(directory)</a></li><li><a href="#process.cwd">process.cwd()</a></li><li><a href="#process.env">process.env</a></li><li><a href="#process.exit">process.exit(code=0)</a></li><li><a href="#process.getgid">process.getgid()</a></li><li><a href="#process.setgid">process.setgid(id)</a></li><li><a href="#process.getuid">process.getuid()</a></li><li><a href="#process.setuid">process.setuid(id)</a></li><li><a href="#process.version">process.version</a></li><li><a href="#process.installPrefix">process.installPrefix</a></li><li><a href="#process.kill">process.kill(pid, signal='SIGTERM')</a></li><li><a href=""></a></li><li><a href="#process.title">process.title</a></li><li><a href="#process.platform">process.platform</a></li><li><a href="#process.memoryUsage">process.memoryUsage()</a></li><li><a href="#process.nextTick">process.nextTick(callback)</a></li><li><a href="#process.umask">process.umask([mask])</a></li></ul></li><li><a href="#util">util</a><ul><li><a href="#util.debug">util.debug(string)</a></li><li><a href="#util.log">util.log(string)</a></li><li><a href="#util.inspect">util.inspect(object, showHidden=false, depth=2)</a></li><li><a href="#util.pump">util.pump(readableStream, writableStream, [callback])</a></li><li><a href="#util.inherits">util.inherits(constructor, superConstructor)</a></li></ul></li><li><a href="#events">Events</a><ul><li><a href="#events.EventEmitter">events.EventEmitter</a><ul><li><a href="#emitter.addListener">emitter.addListener(event, listener)</a></li><li><a href="#emitter.on">emitter.on(event, listener)</a></li><li><a href="#emitter.once">emitter.once(event, listener)</a></li><li><a href="#emitter.removeListener">emitter.removeListener(event, listener)</a></li><li><a href="#emitter.removeAllListeners">emitter.removeAllListeners(event)</a></li><li><a href="#emitter.setMaxListeners">emitter.setMaxListeners(n)</a></li><li><a href="#emitter.listeners">emitter.listeners(event)</a></li><li><a href="#emitter.emit">emitter.emit(event, [arg1], [arg2], [...])</a></li><li><a href="#event_newListener_">Event: 'newListener'</a></li></ul></li></ul></li><li><a href="#buffers">Buffers</a><ul><li><a href="#new_Buffer">new Buffer(size)</a></li><li><a href="#new_Buffer">new Buffer(array)</a></li><li><a href="#new_Buffer">new Buffer(str, encoding='utf8')</a></li><li><a href="#buffer.write">buffer.write(string, offset=0, encoding='utf8')</a></li><li><a href="#buffer.toString">buffer.toString(encoding, start=0, end=buffer.length)</a></li><li><a href="#buffer_index_">buffer[index]</a></li><li><a href="#buffer.isBuffer">Buffer.isBuffer(obj)</a></li><li><a href="#buffer.byteLength">Buffer.byteLength(string, encoding='utf8')</a></li><li><a href="#buffer.length">buffer.length</a></li><li><a href="#buffer.copy">buffer.copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)</a></li><li><a href="#buffer.slice">buffer.slice(start, end=buffer.length)</a></li></ul></li><li><a href="#streams">Streams</a></li><li><a href="#readable_Stream">Readable Stream</a><ul><li><a href="#event_data_">Event: 'data'</a></li><li><a href="#event_end_">Event: 'end'</a></li><li><a href="#event_error_">Event: 'error'</a></li><li><a href="#event_close_">Event: 'close'</a></li><li><a href="#event_fd_">Event: 'fd'</a></li><li><a href="#stream.readable">stream.readable</a></li><li><a href="#stream.setEncoding">stream.setEncoding(encoding)</a></li><li><a href="#stream.pause">stream.pause()</a></li><li><a href="#stream.resume">stream.resume()</a></li><li><a href="#stream.destroy">stream.destroy()</a></li><li><a href="#stream.destroySoon">stream.destroySoon()</a></li><li><a href="#stream.pipe">stream.pipe(destination, [options])</a></li></ul></li><li><a href="#writable_Stream">Writable Stream</a><ul><li><a href="#event_drain_">Event: 'drain'</a></li><li><a href="#event_error_">Event: 'error'</a></li><li><a href="#event_close_">Event: 'close'</a></li><li><a href="#event_pipe_">Event: 'pipe'</a></li><li><a href="#stream.writable">stream.writable</a></li><li><a href="#stream.write">stream.write(string, encoding='utf8', [fd])</a></li><li><a href="#stream.write">stream.write(buffer)</a></li><li><a href="#stream.end">stream.end()</a></li><li><a href="#stream.end">stream.end(string, encoding)</a></li><li><a href="#stream.end">stream.end(buffer)</a></li><li><a href="#stream.destroy">stream.destroy()</a></li><li><a href="#stream.destroySoon">stream.destroySoon()</a></li></ul></li><li><a href="#crypto">Crypto</a><ul><li><a href="#crypto.createCredentials">crypto.createCredentials(details)</a></li><li><a href="#crypto.createHash">crypto.createHash(algorithm)</a></li><li><a href="#hash.update">hash.update(data)</a></li><li><a href="#hash.digest">hash.digest(encoding='binary')</a></li><li><a href="#crypto.createHmac">crypto.createHmac(algorithm, key)</a></li><li><a href="#hmac.update">hmac.update(data)</a></li><li><a href="#hmac.digest">hmac.digest(encoding='binary')</a></li><li><a href="#crypto.createCipher">crypto.createCipher(algorithm, key)</a></li><li><a href="#cipher.update">cipher.update(data, input_encoding='binary', output_encoding='binary')</a></li><li><a href="">'binary')</a></li><li><a href="#crypto.createDecipher">crypto.createDecipher(algorithm, key)</a></li><li><a href="#decipher.update">decipher.update(data, input_encoding='binary', output_encoding='binary')</a></li><li><a href="">'binary')</a></li><li><a href="#crypto.createSign">crypto.createSign(algorithm)</a></li><li><a href="#signer.update">signer.update(data)</a></li><li><a href="#signer.sign">signer.sign(private_key, output_format='binary')</a></li><li><a href="#crypto.createVerify">crypto.createVerify(algorithm)</a></li><li><a href="#verifier.update">verifier.update(data)</a></li><li><a href="#verifier.verify">verifier.verify(object, signature, signature_format='binary')</a></li></ul></li><li><a href="#tLS_">TLS (SSL)</a><ul><li><a href="#s_tls.connect">s = tls.connect(port, [host], [options], callback)</a></li><li><a href="#sTARTTLS">STARTTLS</a></li><li><a href="#tls.Server">tls.Server</a><ul><li><a href="#tls.createServer">tls.createServer(options, secureConnectionListener)</a></li><li><a href="#event_secureConnection_">Event: 'secureConnection'</a></li><li><a href="#server.listen">server.listen(port, [host], [callback])</a></li><li><a href="#server.close">server.close()</a></li><li><a href="#server.maxConnections">server.maxConnections</a></li><li><a href="#server.connections">server.connections</a></li></ul></li></ul></li><li><a href="#file_System">File System</a><ul><li><a href="#fs.rename">fs.rename(path1, path2, [callback])</a></li><li><a href="#fs.renameSync">fs.renameSync(path1, path2)</a></li><li><a href="#fs.truncate">fs.truncate(fd, len, [callback])</a></li><li><a href="#fs.truncateSync">fs.truncateSync(fd, len)</a></li><li><a href="#fs.chown">fs.chown(path, mode, [callback])</a></li><li><a href="#fs.chownSync">fs.chownSync(path, mode)</a></li><li><a href="#fs.fchown">fs.fchown(path, mode, [callback])</a></li><li><a href="#fs.fchownSync">fs.fchownSync(path, mode)</a></li><li><a href="#fs.lchown">fs.lchown(path, mode, [callback])</a></li><li><a href="#fs.lchownSync">fs.lchownSync(path, mode)</a></li><li><a href="#fs.chmod">fs.chmod(path, mode, [callback])</a></li><li><a href="#fs.chmodSync">fs.chmodSync(path, mode)</a></li><li><a href="#fs.fchmod">fs.fchmod(fd, mode, [callback])</a></li><li><a href="#fs.fchmodSync">fs.fchmodSync(path, mode)</a></li><li><a href="#fs.lchmod">fs.lchmod(fd, mode, [callback])</a></li><li><a href="#fs.lchmodSync">fs.lchmodSync(path, mode)</a></li><li><a href="#fs.stat">fs.stat(path, [callback])</a></li><li><a href="#fs.lstat">fs.lstat(path, [callback])</a></li><li><a href="#fs.fstat">fs.fstat(fd, [callback])</a></li><li><a href="#fs.statSync">fs.statSync(path)</a></li><li><a href="#fs.lstatSync">fs.lstatSync(path)</a></li><li><a href="#fs.fstatSync">fs.fstatSync(fd)</a></li><li><a href="">, dstpath, [callback])</a></li><li><a href="#fs.linkSync">fs.linkSync(srcpath, dstpath)</a></li><li><a href="#fs.symlink">fs.symlink(linkdata, path, [callback])</a></li><li><a href="#fs.symlinkSync">fs.symlinkSync(linkdata, path)</a></li><li><a href="#fs.readlink">fs.readlink(path, [callback])</a></li><li><a href="#fs.readlinkSync">fs.readlinkSync(path)</a></li><li><a href="#fs.realpath">fs.realpath(path, [callback])</a></li><li><a href="#fs.realpathSync">fs.realpathSync(path)</a></li><li><a href="#fs.unlink">fs.unlink(path, [callback])</a></li><li><a href="#fs.unlinkSync">fs.unlinkSync(path)</a></li><li><a href="#fs.rmdir">fs.rmdir(path, [callback])</a></li><li><a href="#fs.rmdirSync">fs.rmdirSync(path)</a></li><li><a href="#fs.mkdir">fs.mkdir(path, mode, [callback])</a></li><li><a href="#fs.mkdirSync">fs.mkdirSync(path, mode)</a></li><li><a href="#fs.readdir">fs.readdir(path, [callback])</a></li><li><a href="#fs.readdirSync">fs.readdirSync(path)</a></li><li><a href="#fs.close">fs.close(fd, [callback])</a></li><li><a href="#fs.closeSync">fs.closeSync(fd)</a></li><li><a href="">, flags, [mode], [callback])</a></li><li><a href="#fs.openSync">fs.openSync(path, flags, [mode])</a></li><li><a href="#fs.write">fs.write(fd, buffer, offset, length, position, [callback])</a></li><li><a href="#fs.writeSync">fs.writeSync(fd, buffer, offset, length, position)</a></li><li><a href="#fs.writeSync">fs.writeSync(fd, str, position, encoding='utf8')</a></li><li><a href="">, buffer, offset, length, position, [callback])</a></li><li><a href="#fs.readSync">fs.readSync(fd, buffer, offset, length, position)</a></li><li><a href="#fs.readSync">fs.readSync(fd, length, position, encoding)</a></li><li><a href="#fs.readFile">fs.readFile(filename, [encoding], [callback])</a></li><li><a href="#fs.readFileSync">fs.readFileSync(filename, [encoding])</a></li><li><a href="#fs.writeFile">fs.writeFile(filename, data, encoding='utf8', [callback])</a></li><li><a href="#fs.writeFileSync">fs.writeFileSync(filename, data, encoding='utf8')</a></li><li><a href="#fs.watchFile">fs.watchFile(filename, [options], listener)</a></li><li><a href="#fs.unwatchFile">fs.unwatchFile(filename)</a></li></ul></li><li><a href="#fs.Stats">fs.Stats</a></li><li><a href="#fs.ReadStream">fs.ReadStream</a><ul><li><a href="#event_open_">Event: 'open'</a></li><li><a href="#fs.createReadStream">fs.createReadStream(path, [options])</a></li></ul></li><li><a href="#fs.WriteStream">fs.WriteStream</a><ul><li><a href="#event_open_">Event: 'open'</a></li><li><a href="#fs.createWriteStream">fs.createWriteStream(path, [options])</a></li></ul></li><li><a href="#path">Path</a><ul><li><a href="#path.normalize">path.normalize(p)</a></li><li><a href="#path.join">path.join([path1], [path2], [...])</a></li><li><a href="#path.resolve">path.resolve([from ...], to)</a></li><li><a href="#path.dirname">path.dirname(p)</a></li><li><a href="#path.basename">path.basename(p, [ext])</a></li><li><a href="#path.extname">path.extname(p)</a></li><li><a href="#path.exists">path.exists(p, [callback])</a></li><li><a href="#path.existsSync">path.existsSync(p)</a></li></ul></li><li><a href="#net">net</a><ul><li><a href="#net.createServer">net.createServer([options], [connectionListener])</a></li><li><a href="#net.createConnection">net.createConnection(arguments...)</a></li><li><a href="#net.Server">net.Server</a><ul><li><a href="#server.listen">server.listen(port, [host], [callback])</a></li><li><a href="#server.listen">server.listen(path, [callback])</a></li><li><a href="#server.listenFD">server.listenFD(fd)</a></li><li><a href="#server.pause">server.pause(msecs)</a></li><li><a href="#server.close">server.close()</a></li><li><a href="#server.address">server.address()</a></li><li><a href="#server.maxConnections">server.maxConnections</a></li><li><a href="#server.connections">server.connections</a></li><li><a href="#event_connection_">Event: 'connection'</a></li><li><a href="#event_close_">Event: 'close'</a></li></ul></li><li><a href="#net.Socket">net.Socket</a><ul><li><a href="#new_net.Socket">new net.Socket([options])</a></li><li><a href="#socket.connect">socket.connect(port, [host], [callback])</a></li><li><a href="#socket.connect">socket.connect(path, [callback])</a></li><li><a href="#socket.bufferSize">socket.bufferSize</a></li><li><a href="#socket.setEncoding">socket.setEncoding(encoding=null)</a></li><li><a href="#socket.setSecure">socket.setSecure()</a></li><li><a href="#socket.write">socket.write(data, [encoding], [callback])</a></li><li><a href="#socket.write">socket.write(data, [encoding], [fileDescriptor], [callback])</a></li><li><a href="#socket.end">socket.end([data], [encoding])</a></li><li><a href="#socket.destroy">socket.destroy()</a></li><li><a href="#socket.pause">socket.pause()</a></li><li><a href="#socket.resume">socket.resume()</a></li><li><a href="#socket.setTimeout">socket.setTimeout(timeout, [callback])</a></li><li><a href="#socket.setNoDelay">socket.setNoDelay(noDelay=true)</a></li><li><a href="#socket.setKeepAlive">socket.setKeepAlive(enable=false, [initialDelay])</a></li><li><a href="#socket.address">socket.address()</a></li><li><a href="#socket.remoteAddress">socket.remoteAddress</a></li><li><a href="#event_connect_">Event: 'connect'</a></li><li><a href="#event_data_">Event: 'data'</a></li><li><a href="#event_end_">Event: 'end'</a></li><li><a href="#event_timeout_">Event: 'timeout'</a></li><li><a href="#event_drain_">Event: 'drain'</a></li><li><a href="#event_error_">Event: 'error'</a></li><li><a href="#event_close_">Event: 'close'</a></li></ul></li><li><a href="#net.isIP">net.isIP</a><ul><li><a href="#net.isIP">net.isIP(input)</a></li><li><a href="#net.isIPv4">net.isIPv4(input)</a></li><li><a href="#net.isIPv6">net.isIPv6(input)</a></li></ul></li></ul></li><li><a href="#uDP_Datagram_Sockets">UDP / Datagram Sockets</a><ul><li><a href="#event_message_">Event: 'message'</a></li><li><a href="#event_listening_">Event: 'listening'</a></li><li><a href="#event_close_">Event: 'close'</a></li><li><a href="#dgram.createSocket">dgram.createSocket(type, [callback])</a></li><li><a href="#dgram.send">dgram.send(buf, offset, length, path, [callback])</a></li><li><a href="#dgram.send">dgram.send(buf, offset, length, port, address, [callback])</a></li><li><a href="#dgram.bind">dgram.bind(path)</a></li><li><a href="#dgram.bind">dgram.bind(port, [address])</a></li><li><a href="#dgram.close">dgram.close()</a></li><li><a href="#dgram.address">dgram.address()</a></li><li><a href="#dgram.setBroadcast">dgram.setBroadcast(flag)</a></li><li><a href="#dgram.setTTL">dgram.setTTL(ttl)</a></li><li><a href="#dgram.setMulticastTTL">dgram.setMulticastTTL(ttl)</a></li><li><a href="#dgram.setMulticastLoopback">dgram.setMulticastLoopback(flag)</a></li><li><a href="#dgram.addMembership">dgram.addMembership(multicastAddress, [multicastInterface])</a></li><li><a href="#dgram.dropMembership">dgram.dropMembership(multicastAddress, [multicastInterface])</a></li></ul></li><li><a href="#dNS">DNS</a><ul><li><a href="#dns.lookup">dns.lookup(domain, family=null, callback)</a></li><li><a href="#dns.resolve">dns.resolve(domain, rrtype='A', callback)</a></li><li><a href="#dns.resolve4">dns.resolve4(domain, callback)</a></li><li><a href="#dns.resolve6">dns.resolve6(domain, callback)</a></li><li><a href="#dns.resolveMx">dns.resolveMx(domain, callback)</a></li><li><a href="#dns.resolveTxt">dns.resolveTxt(domain, callback)</a></li><li><a href="#dns.resolveSrv">dns.resolveSrv(domain, callback)</a></li><li><a href="#dns.reverse">dns.reverse(ip, callback)</a></li><li><a href="#dns.resolveNs">dns.resolveNs(domain, callback)</a></li><li><a href="#dns.resolveCname">dns.resolveCname(domain, callback)</a></li></ul></li><li><a href="#hTTP">HTTP</a></li><li><a href="#http.Server">http.Server</a><ul><li><a href="#event_request_">Event: 'request'</a></li><li><a href="#event_connection_">Event: 'connection'</a></li><li><a href="#event_close_">Event: 'close'</a></li><li><a href="#event_checkContinue_">Event: 'checkContinue'</a></li><li><a href="#event_upgrade_">Event: 'upgrade'</a></li><li><a href="#event_clientError_">Event: 'clientError'</a></li><li><a href="#http.createServer">http.createServer([requestListener])</a></li><li><a href="#server.listen">server.listen(port, [hostname], [callback])</a></li><li><a href="#server.listen">server.listen(path, [callback])</a></li><li><a href="#server.close">server.close()</a></li></ul></li><li><a href="#http.ServerRequest">http.ServerRequest</a><ul><li><a href="#event_data_">Event: 'data'</a></li><li><a href="#event_end_">Event: 'end'</a></li><li><a href="#event_close_">Event: 'close'</a></li><li><a href="#request.method">request.method</a></li><li><a href="#request.url">request.url</a></li><li><a href="#request.headers">request.headers</a></li><li><a href="#request.trailers">request.trailers</a></li><li><a href="#request.httpVersion">request.httpVersion</a></li><li><a href="#request.setEncoding">request.setEncoding(encoding=null)</a></li><li><a href="#request.pause">request.pause()</a></li><li><a href="#request.resume">request.resume()</a></li><li><a href="#request.connection">request.connection</a></li></ul></li><li><a href="#http.ServerResponse">http.ServerResponse</a><ul><li><a href="#response.writeContinue">response.writeContinue()</a></li><li><a href="#response.writeHead">response.writeHead(statusCode, [reasonPhrase], [headers])</a></li><li><a href="#response.statusCode">response.statusCode</a></li><li><a href="#response.setHeader">response.setHeader(name, value)</a></li><li><a href="#response.getHeader">response.getHeader(name)</a></li><li><a href="#response.removeHeader">response.removeHeader(name)</a></li><li><a href="#response.write">response.write(chunk, encoding='utf8')</a></li><li><a href="#response.addTrailers">response.addTrailers(headers)</a></li><li><a href="#response.end">response.end([data], [encoding])</a></li></ul></li><li><a href="#http.request">http.request(options, callback)</a></li><li><a href="#http.get">http.get(options, callback)</a></li><li><a href="#http.Agent">http.Agent</a></li><li><a href="#http.getAgent">http.getAgent(host, port)</a><ul><li><a href="#event_upgrade_">Event: 'upgrade'</a></li><li><a href="#agent.maxSockets">agent.maxSockets</a></li><li><a href="#agent.sockets">agent.sockets</a></li><li><a href="#agent.queue">agent.queue</a></li></ul></li><li><a href="#http.ClientRequest">http.ClientRequest</a><ul><li><a href="#event_continue_">Event: 'continue'</a></li><li><a href="#event_response_">Event 'response'</a></li><li><a href="#request.write">request.write(chunk, encoding='utf8')</a></li><li><a href="#request.end">request.end([data], [encoding])</a></li><li><a href="#request.abort">request.abort()</a></li></ul></li><li><a href="#http.ClientResponse">http.ClientResponse</a><ul><li><a href="#event_data_">Event: 'data'</a></li><li><a href="#event_end_">Event: 'end'</a></li><li><a href="#event_close_">Event: 'close'</a></li><li><a href="#response.statusCode">response.statusCode</a></li><li><a href="#response.httpVersion">response.httpVersion</a></li><li><a href="#response.headers">response.headers</a></li><li><a href="#response.trailers">response.trailers</a></li><li><a href="#response.setEncoding">response.setEncoding(encoding=null)</a></li><li><a href="#response.pause">response.pause()</a></li><li><a href="#response.resume">response.resume()</a></li></ul></li><li><a href="#hTTPS">HTTPS</a></li><li><a href="#https.Server">https.Server</a></li><li><a href="#https.createServer">https.createServer(options, [requestListener])</a></li><li><a href="#https.request">https.request(options, callback)</a></li><li><a href="#https.get">https.get(options, callback)</a></li><li><a href="#uRL">URL</a><ul><li><a href="#url.parse">url.parse(urlStr, parseQueryString=false)</a></li><li><a href="#url.format">url.format(urlObj)</a></li><li><a href="#url.resolve">url.resolve(from, to)</a></li></ul></li><li><a href="#query_String">Query String</a><ul><li><a href="#querystring.stringify">querystring.stringify(obj, sep='&', eq='=')</a></li><li><a href="#querystring.parse">querystring.parse(str, sep='&', eq='=')</a></li><li><a href="#querystring.escape">querystring.escape</a></li><li><a href="#querystring.unescape">querystring.unescape</a></li></ul></li><li><a href="#rEPL">REPL</a><ul><li><a href="#repl.start">repl.start(prompt='> ', stream=process.stdin)</a></li><li><a href="#rEPL_Features">REPL Features</a></li></ul></li><li><a href="#executing_JavaScript">Executing JavaScript</a><ul><li><a href="#vm.runInThisContext">vm.runInThisContext(code, [filename])</a></li><li><a href="#vm.runInNewContext">vm.runInNewContext(code, [sandbox], [filename])</a></li><li><a href="#vm.createScript">vm.createScript(code, [filename])</a></li><li><a href="#script.runInThisContext">script.runInThisContext()</a></li><li><a href="#script.runInNewContext">script.runInNewContext([sandbox])</a></li></ul></li><li><a href="#child_Processes">Child Processes</a><ul><li><a href="#event_exit_">Event: 'exit'</a></li><li><a href="#child.stdin">child.stdin</a></li><li><a href="#child.stdout">child.stdout</a></li><li><a href="#child.stderr">child.stderr</a></li><li><a href=""></a></li><li><a href="#child_process.spawn">child_process.spawn(command, args=[], [options])</a></li><li><a href="#child_process.exec">child_process.exec(command, [options], callback)</a></li><li><a href="#child.kill">child.kill(signal='SIGTERM')</a></li></ul></li><li><a href="#assert">Assert</a><ul><li><a href="">, expected, message, operator)</a></li><li><a href="#assert.ok">assert.ok(value, [message])</a></li><li><a href="#assert.equal">assert.equal(actual, expected, [message])</a></li><li><a href="#assert.notEqual">assert.notEqual(actual, expected, [message])</a></li><li><a href="#assert.deepEqual">assert.deepEqual(actual, expected, [message])</a></li><li><a href="#assert.notDeepEqual">assert.notDeepEqual(actual, expected, [message])</a></li><li><a href="#assert.strictEqual">assert.strictEqual(actual, expected, [message])</a></li><li><a href="#assert.notStrictEqual">assert.notStrictEqual(actual, expected, [message])</a></li><li><a href="#assert.throws">assert.throws(block, [error], [message])</a></li><li><a href="#assert.doesNotThrow">assert.doesNotThrow(block, [error], [message])</a></li><li><a href="#assert.ifError">assert.ifError(value)</a></li></ul></li><li><a href="#tTY">TTY</a><ul><li><a href="">, args=[])</a></li><li><a href="#tty.isatty">tty.isatty(fd)</a></li><li><a href="#tty.setRawMode">tty.setRawMode(mode)</a></li><li><a href="#tty.setWindowSize">tty.setWindowSize(fd, row, col)</a></li><li><a href="#tty.getWindowSize">tty.getWindowSize(fd)</a></li></ul></li><li><a href="#os_Module">os Module</a><ul><li><a href="#os.hostname">os.hostname()</a></li><li><a href="#os.type">os.type()</a></li><li><a href="#os.release">os.release()</a></li><li><a href="#os.uptime">os.uptime()</a></li><li><a href="#os.loadavg">os.loadavg()</a></li><li><a href="#os.totalmem">os.totalmem()</a></li><li><a href="#os.freemem">os.freemem()</a></li><li><a href="#os.cpus">os.cpus()</a></li></ul></li><li><a href="#debugger">Debugger</a><ul><li><a href="#advanced_Usage">Advanced Usage</a></li></ul></li></ul></li><li><a href="#appendixes">Appendixes</a><ul><li><a href="#appendix_1_Third_Party_Modules">Appendix 1 - Third Party Modules</a></li></ul><hr /></div>
<h2 id="synopsis">Synopsis</h2>
<p>An example of a <a href="http.html">web server</a> written with Node which responds with 'Hello
<pre><code>var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
console.log('Server running at');</code></pre>
<p>To run the server, put the code into a file called <code>example.js</code> and execute
it with the node program</p>
<pre><code>&gt; node example.js
Server running at</code></pre>
<p>All of the examples in the documentation can be run similarly.</p>
<h2 id="global_Objects">Global Objects</h2>
<p>These object 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.</p>
<h3 id="global">global</h3>
<p>The global namespace object.</p>
<p>In browsers, the top-level scope is the global scope. That means that in
browsers if you're in the global scope <code>var something</code> will define a global
variable. In Node this is different. The top-level scope is not the global
scope; <code>var something</code> inside a Node module will be local to that module.</p>
<h3 id="process">process</h3>
<p>The process object. See the <a href="process.html#process">process object</a> section.</p>
<h3 id="console">console</h3>
<p>Used to print to stdout and stderr. See the <a href="stdio.html">stdio</a> section.</p>
<h3 id="require">require()</h3>
<p>To require modules. See the <a href="modules.html#modules">Modules</a> section.
<code>require</code> isn't actually a global but rather local to each module.</p>
<h3 id="require.resolve">require.resolve()</h3>
<p>Use the internal <code>require()</code> machinery to look up the location of a module,
but rather than loading the module, just return the resolved filename.</p>
<h3 id="require.cache">require.cache</h3>
<p>Modules are cached in this object when they are required. By deleting a key
value from this object, the next <code>require</code> will reload the module.</p>
<h3 id="require.paths">require.paths</h3>
<p>An array of search paths for <code>require()</code>. This array can be modified to add
custom paths.</p>
<p>Example: add a new path to the beginning of the search list</p>
<h3 id="__filename">__filename</h3>
<p>The filename of the script being executed. This is the absolute path, and not necessarily
the same filename passed in as a command line argument.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
// /Users/mjr/example.js</code></pre>
<p><code>__filename</code> isn't actually a global but rather local to each module.</p>
<h3 id="__dirname">__dirname</h3>
<p>The dirname of the script being executed.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
// /Users/mjr</code></pre>
<p><code>__dirname</code> isn't actually a global but rather local to each module.</p>
<h3 id="module">module</h3>
<p>A reference to the current module. In particular
<code>module.exports</code> is the same as the <code>exports</code> object. See <code>src/node.js</code>
for more information.
<code>module</code> isn't actually a global but rather local to each module.</p>
<h3 id="exports">exports</h3>
<p>An object which is shared between all instances of the current module and
made accessible through <code>require()</code>.
<code>exports</code> is the same as the <code>module.exports</code> object. See <code>src/node.js</code>
for more information.
<code>exports</code> isn't actually a global but rather local to each module.</p>
<h3 id="setTimeout">setTimeout(cb, ms)</h3>
<h3 id="clearTimeout">clearTimeout(t)</h3>
<h3 id="setInterval">setInterval(cb, ms)</h3>
<h3 id="clearInterval">clearInterval(t)</h3>
<p>The timer functions are global variables. See the <a href="timers.html">timers</a> section.</p>
<h2 id="console">console</h2>
<p>Browser-like object for printing to stdout and stderr.</p>
<h3 id="console.log">console.log()</h3>
<p>Prints to stdout with newline. This function can take multiple arguments in a
<code>printf()</code>-like way. Example:</p>
<pre><code>console.log('count: %d', count);</code></pre>
<p>If formating elements are not found in the first string then <code>util.inspect</code>
is used on each argument.</p>
<h3 id=""></h3>
<p>Same as <code>console.log</code>.</p>
<h3 id="console.warn">console.warn()</h3>
<h3 id="console.error">console.error()</h3>
<p>Same as <code>console.log</code> but prints to stderr.</p>
<h3 id="console.dir">console.dir(obj)</h3>
<p>Uses <code>util.inspect</code> on <code>obj</code> and prints resulting string to stderr.</p>
<h3 id="console.time">console.time(label)</h3>
<p>Mark a time.</p>
<h3 id="console.timeEnd">console.timeEnd(label)</h3>
<p>Finish timer, record output. Example</p>
for (var i = 0; i &lt; 100; i++) {
<h3 id="console.trace">console.trace()</h3>
<p>Print a stack trace to stderr of the current position.</p>
<h3 id="console.assert">console.assert()</h3>
<p>Same as <code>assert.ok()</code>.</p>
<h2 id="timers">Timers</h2>
<h3 id="setTimeout">setTimeout(callback, delay, [arg], [...])</h3>
<p>To schedule execution of <code>callback</code> after <code>delay</code> milliseconds. Returns a
<code>timeoutId</code> for possible use with <code>clearTimeout()</code>. Optionally, you can
also pass arguments to the callback.</p>
<h3 id="clearTimeout">clearTimeout(timeoutId)</h3>
<p>Prevents a timeout from triggering.</p>
<h3 id="setInterval">setInterval(callback, delay, [arg], [...])</h3>
<p>To schedule the repeated execution of <code>callback</code> every <code>delay</code> milliseconds.
Returns a <code>intervalId</code> for possible use with <code>clearInterval()</code>. Optionally,
you can also pass arguments to the callback.</p>
<h3 id="clearInterval">clearInterval(intervalId)</h3>
<p>Stops a interval from triggering.</p>
<h2 id="modules">Modules</h2>
<p>Node has a simple module loading system. In Node, files and modules are in
one-to-one correspondence. As an example, <code>foo.js</code> loads the module
<code>circle.js</code> in the same directory.</p>
<p>The contents of <code>foo.js</code>:</p>
<pre><code>var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
+ circle.area(4));</code></pre>
<p>The contents of <code>circle.js</code>:</p>
<pre><code>var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
exports.circumference = function (r) {
return 2 * PI * r;
<p>The module <code>circle.js</code> has exported the functions <code>area()</code> and
<code>circumference()</code>. To export an object, add to the special <code>exports</code>
local to the module will be private. In this example the variable <code>PI</code> is
private to <code>circle.js</code>.</p>
<h3 id="core_Modules">Core Modules</h3>
<p>Node has several modules compiled into the binary. These modules are
described in greater detail elsewhere in this documentation.</p>
<p>The core modules are defined in node's source in the <code>lib/</code> folder.</p>
<p>Core modules are always preferentially loaded if their identifier is
passed to <code>require()</code>. For instance, <code>require('http')</code> will always
return the built in HTTP module, even if there is a file by that name.</p>
<h3 id="file_Modules">File Modules</h3>
<p>If the exact filename is not found, then node will attempt to load the
required filename with the added extension of <code>.js</code>, and then <code>.node</code>.</p>
<p><code>.js</code> files are interpreted as JavaScript text files, and <code>.node</code> files
are interpreted as compiled addon modules loaded with <code>dlopen</code>.</p>
<p>A module prefixed with <code>'/'</code> is an absolute path to the file. For
example, <code>require('/home/marco/foo.js')</code> will load the file at
<p>A module prefixed with <code>'./'</code> is relative to the file calling <code>require()</code>.
That is, <code>circle.js</code> must be in the same directory as <code>foo.js</code> for
<code>require('./circle')</code> to find it.</p>
<p>Without a leading '/' or './' to indicate a file, the module is either a
"core module" or is loaded from a <code>node_modules</code> folder.</p>
<h3 id="loading_from_node_modules_Folders">Loading from `node_modules` Folders</h3>
<p>If the module identifier passed to <code>require()</code> is not a native module,
and does not begin with <code>'/'</code>, <code>'../'</code>, or <code>'./'</code>, then node starts at the
parent directory of the current module, and adds <code>/node_modules</code>, and
attempts to load the module from that location.</p>
<p>If it is not found there, then it moves to the parent directory, and so
on, until the root of the tree is reached.</p>
<p>For example, if the file at <code>'/home/ry/projects/foo.js'</code> called
<code>require('bar.js')</code>, then node would look in the following locations, in
this order:</p>
<p>This allows programs to localize their dependencies, so that they do not
<h3 id="folders_as_Modules">Folders as Modules</h3>
<p>It is convenient to organize programs and libraries into self-contained
directories, and then provide a single entry point to that library.
There are three ways in which a folder may be passed to <code>require()</code> as
an argument.</p>
<p>The first is to create a <code>package.json</code> file in the root of the folder,
which specifies a <code>main</code> module. An example package.json file might
look like this:</p>
<pre><code>{ "name" : "some-library",
"main" : "./lib/some-library.js" }</code></pre>
<p>If this was in a folder at <code>./some-library</code>, then
<code>require('./some-library')</code> would attempt to load
<p>This is the extent of Node's awareness of package.json files.</p>
<p>If there is no package.json file present in the directory, then node
will attempt to load an <code>index.js</code> or <code>index.node</code> file out of that
directory. For example, if there was no package.json file in the above
example, then <code>require('./some-library')</code> would attempt to load:</p>
<h3 id="caching">Caching</h3>
<p>Modules are cached after the first time they are loaded. This means
(among other things) that every call to <code>require('foo')</code> will get
exactly the same object returned, if it would resolve to the same file.</p>
<p>Multiple calls to <code>require('foo')</code> may not cause the module code to be
executed multiple times. This is an important feature. With it,
"partially done" objects can be returned, thus allowing transitive
dependencies to be loaded even when they would cause cycles.</p>
<p>If you want to have a module execute code multiple times, then export a
function, and call that function.</p>
<h4 id="module_Caching_Caveats">Module Caching Caveats</h4>
<p>Modules are cached based on their resolved filename. Since modules may
resolve to a different filename based on the location of the calling
module (loading from <code>node_modules</code> folders), it is not a <em>guarantee</em>
that <code>require('foo')</code> will always return the exact same object, if it
would resolve to different files.</p>
<h3 id="module.exports">module.exports</h3>
<p>The <code>exports</code> object is created by the Module system. Sometimes this is not
acceptable, many want their module to be an instance of some class. To do this
assign the desired export object to <code>module.exports</code>. For example suppose we
were making a module called <code>a.js</code></p>
<pre><code>var EventEmitter = require('events').EventEmitter;
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(function() {
}, 1000);</code></pre>
<p>Then in another file we could do</p>
<pre><code>var a = require('./a');
a.on('ready', function() {
console.log('module a is ready');
<p>Note that assignment to <code>module.exports</code> must be done immediately. It cannot be
done in any callbacks. This does not work:</p>
<pre><code>setTimeout(function() {
module.exports = { a: "hello" };
}, 0);</code></pre>
<pre><code>var x = require('./x');
<h3 id="all_Together...">All Together...</h3>
<p>To get the exact filename that will be loaded when <code>require()</code> is called, use
the <code>require.resolve()</code> function.</p>
<p>Putting together all of the above, here is the high-level algorithm
in pseudocode of what require.resolve does:</p>
<pre><code>require(X) from module at path Y
1. If X is a core module,
a. return the core module
2. If X begins with './' or '/' or '../'
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"
1. If X is a file, load X as JavaScript text. STOP
2. If X.js is a file, load X.js as JavaScript text. STOP
3. If X.node is a file, load X.node as binary addon. STOP
1. If X/package.json is a file,
a. Parse X/package.json, and look for "main" field.
b. let M = X + (json main field)
2. LOAD_AS_FILE(X/index)
2. for each DIR in DIRS:
1. let PARTS = path split(START)
2. let ROOT = index of first instance of "node_modules" in PARTS, or 0
3. let I = count of PARTS - 1
4. let DIRS = []
5. while I &gt; ROOT,
a. if PARTS[I] = "node_modules" CONTINUE
c. DIR = path join(PARTS[0 .. I] + "node_modules")
c. let I = I - 1
6. return DIRS</code></pre>
<h3 id="loading_from_the_require.paths_Folders">Loading from the `require.paths` Folders</h3>
<p>In node, <code>require.paths</code> is an array of strings that represent paths to
be searched for modules when they are not prefixed with <code>'/'</code>, <code>'./'</code>, or
<code>'../'</code>. For example, if require.paths were set to:</p>
<pre><code>[ '/home/micheil/.node_modules',
'/usr/local/lib/node_modules' ]</code></pre>
<p>Then calling <code>require('bar/baz.js')</code> would search the following
<ul><li>1: <code>'/home/micheil/.node_modules/bar/baz.js'</code></li><li>2: <code>'/usr/local/lib/node_modules/bar/baz.js'</code></li></ul>
<p>The <code>require.paths</code> array can be mutated at run time to alter this
<p>It is set initially from the <code>NODE_PATH</code> environment variable, which is
a colon-delimited list of absolute paths. In the previous example,
the <code>NODE_PATH</code> environment variable might have been set to:</p>
<p>Loading from the <code>require.paths</code> locations is only performed if the
module could not be found using the <code>node_modules</code> algorithm above.
Global modules are lower priority than bundled dependencies.</p>
<h4 id="_Note_Please_Avoid_Modifying_require.paths_">**Note:** Please Avoid Modifying `require.paths`</h4>
<p><code>require.paths</code> may disappear in a future release.</p>
<p>While it seemed like a good idea at the time, and enabled a lot of
useful experimentation, in practice a mutable <code>require.paths</code> list is
often a troublesome source of confusion and headaches.</p>
<h5 id="setting_require.paths_to_some_other_value_does_nothing.">Setting `require.paths` to some other value does nothing.</h5>
<p>This does not do what one might expect:</p>
<pre><code>require.paths = [ '/usr/lib/node' ];</code></pre>
<p>All that does is lose the reference to the <em>actual</em> node module lookup
paths, and create a new reference to some other thing that isn't used
for anything.</p>
<h5 id="putting_relative_paths_in_require.paths_is..._weird.">Putting relative paths in `require.paths` is... weird.</h5>
<p>If you do this:</p>
<p>then it does <em>not</em> add the full resolved path to where <code>./lib</code>
is on the filesystem. Instead, it literally adds <code>'./lib'</code>,
meaning that if you do <code>require('y.js')</code> in <code>/a/b/x.js</code>, then it'll look
in <code>/a/b/lib/y.js</code>. If you then did <code>require('y.js')</code> in
<code>/l/m/n/o/p.js</code>, then it'd look in <code>/l/m/n/o/lib/y.js</code>.</p>
<p>In practice, people have used this as an ad hoc way to bundle
dependencies, but this technique is brittle.</p>
<h5 id="zero_Isolation">Zero Isolation</h5>
<p>There is (by regrettable design), only one <code>require.paths</code> array used by
all modules.</p>
<p>As a result, if one node program comes to rely on this behavior, it may
permanently and subtly alter the behavior of all other node programs in
the same process. As the application stack grows, we tend to assemble
functionality, and those parts interact in ways that are difficult to
<h3 id="accessing_the_main_module">Accessing the main module</h3>
<p>When a file is run directly from Node, <code>require.main</code> is set to its
<code>module</code>. That means that you can determine whether a file has been run
directly by testing</p>
<pre><code>require.main === module</code></pre>
<p>For a file <code>foo.js</code>, this will be <code>true</code> if run via <code>node foo.js</code>, but
<code>false</code> if run by <code>require('./foo')</code>.</p>
<p>Because <code>module</code> provides a <code>filename</code> property (normally equivalent to
<code>__filename</code>), the entry point of the current application can be obtained
by checking <code>require.main.filename</code>.</p>
<h2 id="addenda_Package_Manager_Tips">Addenda: Package Manager Tips</h2>
<p>The semantics of Node's <code>require()</code> function were designed to be general
enough to support a number of sane directory structures. Package manager
programs such as <code>dpkg</code>, <code>rpm</code>, and <code>npm</code> will hopefully find it possible to
build native packages from Node modules without modification.</p>
<p>Below we give a suggested directory structure that could work:</p>
<p>Let's say that we wanted to have the folder at
<code>/usr/lib/node/&lt;some-package&gt;/&lt;some-version&gt;</code> hold the contents of a
specific version of a package.</p>
<p>Packages can depend on one another. In order to install package <code>foo</code>, you
may have to install a specific version of package <code>bar</code>. The <code>bar</code> package
may itself have dependencies, and in some cases, these dependencies may even
collide or form cycles.</p>
<p>Since Node looks up the <code>realpath</code> of any modules it loads (that is,
resolves symlinks), and then looks for their dependencies in the
<code>node_modules</code> folders as described above, this situation is very simple to
resolve with the following architecture:</p>
<ul><li><code>/usr/lib/node/foo/1.2.3/</code> - Contents of the <code>foo</code> package, version 1.2.3.</li><li><code>/usr/lib/node/bar/4.3.2/</code> - Contents of the <code>bar</code> package that <code>foo</code>
depends on.</li><li><code>/usr/lib/node/foo/1.2.3/node_modules/bar</code> - Symbolic link to
<code>/usr/lib/node/bar/4.3.2/</code>.</li><li><code>/usr/lib/node/bar/4.3.2/node_modules/*</code> - Symbolic links to the packages
that <code>bar</code> depends on.</li></ul>
<p>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.</p>
<p>When the code in the <code>foo</code> package does <code>require('bar')</code>, it will get the
version that is symlinked into <code>/usr/lib/node/foo/1.2.3/node_modules/bar</code>.
Then, when the code in the <code>bar</code> package calls <code>require('quux')</code>, it'll get
the version that is symlinked into
<p>Furthermore, to make the module lookup process even more optimal, rather
than putting packages directly in <code>/usr/lib/node</code>, we could put them in
<code>/usr/lib/node_modules/&lt;name&gt;/&lt;version&gt;</code>. Then node will not bother
looking for missing dependencies in <code>/usr/node_modules</code> or <code>/node_modules</code>.</p>
<p>In order to make modules available to the node REPL, it might be useful to
also add the <code>/usr/lib/node_modules</code> folder to the <code>$NODE_PATH</code> environment
variable. Since the module lookups using <code>node_modules</code> folders are all
relative, and based on the real path of the files making the calls to
<code>require()</code>, the packages themselves can be anywhere.</p>
<h2 id="addons">Addons</h2>
<p>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:</p>
<ul><li><p>V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
creating objects, calling functions, etc. Documented mostly in the
<code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node source tree).</p></li><li><p>libev, 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 libev. That is, if you perform
any I/O, libev will need to be used. Node uses the <code>EV_DEFAULT</code> event
loop. Documentation can be found <a href="">here</a>.</p></li><li><p>libeio, C thread pool library. Used to execute blocking POSIX system
calls asynchronously. Mostly wrappers already exist for such calls, in
<code>src/</code> so you will probably not need to use it. If you do need it,
look at the header file <code>deps/libeio/eio.h</code>.</p></li><li><p>Internal Node libraries. Most importantly is the <code>node::ObjectWrap</code>
class which you will likely want to derive from.</p></li><li><p>Others. Look in <code>deps/</code> for what else is available.</p></li></ul>
<p>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
<p>To get started let's make a small Addon which does the following except in
<pre><code>exports.hello = 'world';</code></pre>
<p>To get started we create a file <code></code>:</p>
<pre><code>#include &lt;v8.h&gt;
using namespace v8;
extern "C" void
init (Handle&lt;Object&gt; target)
HandleScope scope;
target-&gt;Set(String::New("hello"), String::New("world"));
<p>This source code needs to be built into <code>hello.node</code>, the binary Addon. To
do this we create a file called <code>wscript</code> which is python code and looks
like this:</p>
<pre><code>srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'
def set_options(opt):
def configure(conf):
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon') = 'hello'
obj.source = ''</code></pre>
<p>Running <code>node-waf configure build</code> will create a file
<code>build/default/hello.node</code> which is our Addon.</p>
<p><code>node-waf</code> is just <a href="">WAF</a>, the python-based build system. <code>node-waf</code> is
provided for the ease of users.</p>
<p>All Node addons must export a function called <code>init</code> with this signature:</p>
<pre><code>extern 'C' void init (Handle&lt;Object&gt; target)</code></pre>
<p>For the moment, that is all the documentation on addons. Please see
<a href=""></a> for a real example.</p>
<h2 id="process">process</h2>
<p>The <code>process</code> object is a global object and can be accessed from anywhere.
It is an instance of <code>EventEmitter</code>.</p>
<h3 id="event_exit_">Event: 'exit'</h3>
<p><code>function () {}</code></p>
<p>Emitted when the process is about to exit. This is a good hook to perform
constant time checks of the module's state (like for unit tests). The main
event loop will no longer be run after the 'exit' callback finishes, so
timers may not be scheduled.</p>
<p>Example of listening for <code>exit</code>:</p>
<pre><code>process.on('exit', function () {
process.nextTick(function () {
console.log('This will not run');
console.log('About to exit.');
<h3 id="event_uncaughtException_">Event: 'uncaughtException'</h3>
<p><code>function (err) { }</code></p>
<p>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.</p>
<p>Example of listening for <code>uncaughtException</code>:</p>
<pre><code>process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
setTimeout(function () {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
console.log('This will not run.');</code></pre>
<p>Note that <code>uncaughtException</code> is a very crude mechanism for exception
handling. Using try / catch in your program will give you more control over
your program's flow. Especially for server programs that are designed to
stay running forever, <code>uncaughtException</code> can be a useful safety mechanism.</p>
<h3 id="signal_Events">Signal Events</h3>
<p><code>function () {}</code></p>
<p>Emitted when the processes receives a signal. See sigaction(2) for a list of
standard POSIX signal names such as SIGINT, SIGUSR1, etc.</p>
<p>Example of listening for <code>SIGINT</code>:</p>
<pre><code>// Start reading from stdin so we don't exit.
process.on('SIGINT', function () {
console.log('Got SIGINT. Press Control-D to exit.');
<p>An easy way to send the <code>SIGINT</code> signal is with <code>Control-C</code> in most terminal
<h3 id="process.stdout">process.stdout</h3>
<p>A <code>Writable Stream</code> to <code>stdout</code>.</p>
<p>Example: the definition of <code>console.log</code></p>
<pre><code>console.log = function (d) {
process.stdout.write(d + '\n');
<h3 id="process.stderr">process.stderr</h3>
<p>A writable stream to stderr. Writes on this stream are blocking.</p>
<h3 id="process.stdin">process.stdin</h3>
<p>A <code>Readable Stream</code> for stdin. The stdin stream is paused by default, so one
must call <code>process.stdin.resume()</code> to read from it.</p>
<p>Example of opening standard input and listening for both events:</p>
process.stdin.on('data', function (chunk) {
process.stdout.write('data: ' + chunk);
process.stdin.on('end', function () {
<h3 id="process.argv">process.argv</h3>
<p>An array containing the command line arguments. The first element will be
'node', the second element will be the name of the JavaScript file. The
next elements will be any additional command line arguments.</p>
<pre><code>// print process.argv
process.argv.forEach(function (val, index, array) {
console.log(index + ': ' + val);
<p>This will generate:</p>
<pre><code>$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four</code></pre>
<h3 id="process.execPath">process.execPath</h3>
<p>This is the absolute pathname of the executable that started the process.</p>
<h3 id="process.chdir">process.chdir(directory)</h3>
<p>Changes the current working directory of the process or throws an exception if that fails.</p>
<pre><code>console.log('Starting directory: ' + process.cwd());
try {
console.log('New directory: ' + process.cwd());
catch (err) {
console.log('chdir: ' + err);
<h3 id="process.cwd">process.cwd()</h3>
<p>Returns the current working directory of the process.</p>
<pre><code>console.log('Current directory: ' + process.cwd());</code></pre>
<h3 id="process.env">process.env</h3>
<p>An object containing the user environment. See environ(7).</p>
<h3 id="process.exit">process.exit(code=0)</h3>
<p>Ends the process with the specified <code>code</code>. If omitted, exit uses the
'success' code <code>0</code>.</p>
<p>To exit with a 'failure' code:</p>
<p>The shell that executed node should see the exit code as 1.</p>
<h3 id="process.getgid">process.getgid()</h3>
<p>Gets the group identity of the process. (See getgid(2).)
This is the numerical group id, not the group name.</p>
<pre><code>console.log('Current gid: ' + process.getgid());</code></pre>
<h3 id="process.setgid">process.setgid(id)</h3>
<p>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.</p>
<pre><code>console.log('Current gid: ' + process.getgid());
try {
console.log('New gid: ' + process.getgid());
catch (err) {
console.log('Failed to set gid: ' + err);
<h3 id="process.getuid">process.getuid()</h3>
<p>Gets the user identity of the process. (See getuid(2).)
This is the numerical userid, not the username.</p>
<pre><code>console.log('Current uid: ' + process.getuid());</code></pre>
<h3 id="process.setuid">process.setuid(id)</h3>
<p>Sets the user identity of the process. (See setuid(2).) This accepts either
a numerical ID or a username string. If a username is specified, this method
blocks while resolving it to a numerical ID.</p>
<pre><code>console.log('Current uid: ' + process.getuid());
try {
console.log('New uid: ' + process.getuid());
catch (err) {
console.log('Failed to set uid: ' + err);
<h3 id="process.version">process.version</h3>
<p>A compiled-in property that exposes <code>NODE_VERSION</code>.</p>
<pre><code>console.log('Version: ' + process.version);</code></pre>
<h3 id="process.installPrefix">process.installPrefix</h3>
<p>A compiled-in property that exposes <code>NODE_PREFIX</code>.</p>
<pre><code>console.log('Prefix: ' + process.installPrefix);</code></pre>
<h3 id="process.kill">process.kill(pid, signal='SIGTERM')</h3>
<p>Send a signal to a process. <code>pid</code> is the process id and <code>signal</code> is the
string describing the signal to send. Signal names are strings like
'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGTERM'.
See kill(2) for more information.</p>
<p>Note that just because the name of this function is <code>process.kill</code>, it is
really just a signal sender, like the <code>kill</code> system call. The signal sent
may do something other than kill the target process.</p>
<p>Example of sending a signal to yourself:</p>
<pre><code>process.on('SIGHUP', function () {
console.log('Got SIGHUP signal.');
setTimeout(function () {
}, 100);
process.kill(, 'SIGHUP');</code></pre>
<h3 id=""></h3>
<p>The PID of the process.</p>
<pre><code>console.log('This process is pid ' +;</code></pre>
<h3 id="process.title">process.title</h3>
<p>Getter/setter to set what is displayed in 'ps'.</p>
<h3 id="process.platform">process.platform</h3>
<p>What platform you're running on. <code>'linux2'</code>, <code>'darwin'</code>, etc.</p>
<pre><code>console.log('This platform is ' + process.platform);</code></pre>
<h3 id="process.memoryUsage">process.memoryUsage()</h3>
<p>Returns an object describing the memory usage of the Node process.</p>
<pre><code>var util = require('util');
<p>This will generate:</p>
<pre><code>{ rss: 4935680,
vsize: 41893888,
heapTotal: 1826816,
heapUsed: 650472 }</code></pre>
<p><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.</p>
<h3 id="process.nextTick">process.nextTick(callback)</h3>
<p>On the next loop around the event loop call this callback.
This is <em>not</em> a simple alias to <code>setTimeout(fn, 0)</code>, it's much more
<pre><code>process.nextTick(function () {
console.log('nextTick callback');
<h3 id="process.umask">process.umask([mask])</h3>
<p>Sets or reads the process's file mode creation mask. Child processes inherit
the mask from the parent process. Returns the old mask if <code>mask</code> argument is
given, otherwise returns the current mask.</p>
<pre><code>var oldmask, newmask = 0644;
oldmask = process.umask(newmask);
console.log('Changed umask from: ' + oldmask.toString(8) +
' to ' + newmask.toString(8));</code></pre>
<h2 id="util">util</h2>
<p>These functions are in the module <code>'util'</code>. Use <code>require('util')</code> to access
<h3 id="util.debug">util.debug(string)</h3>
<p>A synchronous output function. Will block the process and
output <code>string</code> immediately to <code>stderr</code>.</p>
<pre><code>require('util').debug('message on stderr');</code></pre>
<h3 id="util.log">util.log(string)</h3>
<p>Output with timestamp on <code>stdout</code>.</p>
<pre><code>require('util').log('Timestamped message.');</code></pre>
<h3 id="util.inspect">util.inspect(object, showHidden=false, depth=2)</h3>
<p>Return a string representation of <code>object</code>, which is useful for debugging.</p>
<p>If <code>showHidden</code> is <code>true</code>, then the object's non-enumerable properties will be
shown too.</p>
<p>If <code>depth</code> is provided, it tells <code>inspect</code> how many times to recurse while
formatting the object. This is useful for inspecting large complicated objects.</p>
<p>The default is to only recurse twice. To make it recurse indefinitely, pass
in <code>null</code> for <code>depth</code>.</p>
<p>Example of inspecting all properties of the <code>util</code> object:</p>
<pre><code>var util = require('util');
console.log(util.inspect(util, true, null));</code></pre>
<h3 id="util.pump">util.pump(readableStream, writableStream, [callback])</h3>
<p>Read the data from <code>readableStream</code> and send it to the <code>writableStream</code>.
When <code>writableStream.write(data)</code> returns <code>false</code> <code>readableStream</code> will be
paused until the <code>drain</code> event occurs on the <code>writableStream</code>. <code>callback</code> gets
an error as its only argument and is called when <code>writableStream</code> is closed or
when an error occurs.</p>
<h3 id="util.inherits">util.inherits(constructor, superConstructor)</h3>
<p>Inherit the prototype methods from one
<a href="">constructor</a>
into another. The prototype of <code>constructor</code> will be set to a new
object created from <code>superConstructor</code>.</p>
<p>As an additional convenience, <code>superConstructor</code> will be accessible
through the <code>constructor.super_</code> property.</p>
<pre><code>var util = require("util");
var events = require("events");
function MyStream() {;
util.inherits(MyStream, events.EventEmitter);
MyStream.prototype.write = function(data) {
this.emit("data", data);
var stream = new MyStream();
console.log(stream instanceof events.EventEmitter); // true
console.log(MyStream.super_ === events.EventEmitter); // true
stream.on("data", function(data) {
console.log('Received data: "' + data + '"');
stream.write("It works!"); // Received data: "It works!"</code></pre>
<h2 id="events">Events</h2>
<p>Many objects in Node emit events: a <code>net.Server</code> emits an event each time
a peer connects to it, a <code>fs.readStream</code> emits an event when the file is
opened. All objects which emit events are instances of <code>events.EventEmitter</code>.
You can access this module by doing: <code>require("events");</code></p>
<p>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.</p>
<p>Functions can then be attached to objects, to be executed when an event
is emitted. These functions are called <em>listeners</em>.</p>
<h3 id="events.EventEmitter">events.EventEmitter</h3>
<p>To access the EventEmitter class, <code>require('events').EventEmitter</code>.</p>
<p>When an <code>EventEmitter</code> instance experiences an error, the typical action is
to emit an <code>'error'</code> event. Error events are treated as a special case in node.
If there is no listener for it, then the default action is to print a stack
trace and exit the program.</p>
<p>All EventEmitters emit the event <code>'newListener'</code> when new listeners are
<h4 id="emitter.addListener">emitter.addListener(event, listener)</h4>
<h4 id="emitter.on">emitter.on(event, listener)</h4>
<p>Adds a listener to the end of the listeners array for the specified event.</p>
<pre><code>server.on('connection', function (stream) {
console.log('someone connected!');
<h4 id="emitter.once">emitter.once(event, listener)</h4>
<p>Adds a <strong>one time</strong> listener for the event. The listener is
invoked only the first time the event is fired, after which
it is removed.</p>
<pre><code>server.once('connection', function (stream) {
console.log('Ah, we have our first user!');
<h4 id="emitter.removeListener">emitter.removeListener(event, listener)</h4>
<p>Remove a listener from the listener array for the specified event.
<strong>Caution</strong>: changes array indices in the listener array behind the listener.</p>
<pre><code>var callback = function(stream) {
console.log('someone connected!');
server.on('connection', callback);
// ...
server.removeListener('connection', callback);</code></pre>
<h4 id="emitter.removeAllListeners">emitter.removeAllListeners(event)</h4>
<p>Removes all listeners from the listener array for the specified event.</p>
<h4 id="emitter.setMaxListeners">emitter.setMaxListeners(n)</h4>
<p>By default EventEmitters will print a warning if more than 10 listeners are
added to it. This is a useful default which helps finding memory leaks.
Obviously not all Emitters should be limited to 10. This function allows
that to be increased. Set to zero for unlimited.</p>
<h4 id="emitter.listeners">emitter.listeners(event)</h4>
<p>Returns an array of listeners for the specified event. This array can be
manipulated, e.g. to remove listeners.</p>
<pre><code>server.on('connection', function (stream) {
console.log('someone connected!');
console.log(util.inspect(server.listeners('connection')); // [ [Function] ]</code></pre>
<h4 id="emitter.emit">emitter.emit(event, [arg1], [arg2], [...])</h4>
<p>Execute each of the listeners in order with the supplied arguments.</p>
<h4 id="event_newListener_">Event: 'newListener'</h4>
<p><code>function (event, listener) { }</code></p>
<p>This event is emitted any time someone adds a new listener.</p>
<h2 id="buffers">Buffers</h2>
<p>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.</p>
<p>Raw data is stored in instances of the <code>Buffer</code> class. A <code>Buffer</code> is similar
to an array of integers but corresponds to a raw memory allocation outside
the V8 heap. A <code>Buffer</code> cannot be resized.</p>
<p>The <code>Buffer</code> object is global.</p>
<p>Converting between Buffers and JavaScript string objects requires an explicit encoding
method. Here are the different string encodings;</p>
<ul><li><p><code>'ascii'</code> - for 7 bit ASCII data only. This encoding method is very fast, and will
strip the high bit if set.
Note that this encoding converts a null character (<code>'\0'</code> or <code>'\u0000'</code>) into
<code>0x20</code> (character code of a space). If you want to convert a null character
into <code>0x00</code>, you should use <code>'utf8'</code>.</p></li><li><p><code>'utf8'</code> - Multi byte encoded Unicode characters. Many web pages and other document formats use UTF-8.</p></li><li><p><code>'ucs2'</code> - 2-bytes, little endian encoded Unicode characters. It can encode
only BMP(Basic Multilingual Plane, U+0000 - U+FFFF).</p></li><li><p><code>'base64'</code> - Base64 string encoding.</p></li><li><p><code>'binary'</code> - A way of encoding raw binary data into strings by using only
the first 8 bits of each character. This encoding method is deprecated and
should be avoided in favor of <code>Buffer</code> objects where possible. This encoding
will be removed in future versions of Node.</p></li></ul>
<h3 id="new_Buffer">new Buffer(size)</h3>
<p>Allocates a new buffer of <code>size</code> octets.</p>
<h3 id="new_Buffer">new Buffer(array)</h3>
<p>Allocates a new buffer using an <code>array</code> of octets.</p>
<h3 id="new_Buffer">new Buffer(str, encoding='utf8')</h3>
<p>Allocates a new buffer containing the given <code>str</code>.</p>
<h3 id="buffer.write">buffer.write(string, offset=0, encoding='utf8')</h3>
<p>Writes <code>string</code> to the buffer at <code>offset</code> using the given encoding. Returns
number of octets written. If <code>buffer</code> did not contain enough space to fit
the entire string, it will write a partial amount of the string.
The method will not write partial characters.</p>
<p>Example: write a utf8 string into a buffer, then print it</p>
<pre><code>buf = new Buffer(256);
len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(len + " bytes: " + buf.toString('utf8', 0, len));</code></pre>
<p>The number of characters written (which may be different than the number of
bytes written) is set in <code>Buffer._charsWritten</code> and will be overwritten the
next time <code>buf.write()</code> is called.</p>
<h3 id="buffer.toString">buffer.toString(encoding, start=0, end=buffer.length)</h3>
<p>Decodes and returns a string from buffer data encoded with <code>encoding</code>
beginning at <code>start</code> and ending at <code>end</code>.</p>
<p>See <code>buffer.write()</code> example, above.</p>
<h3 id="buffer_index_">buffer[index]</h3>
<p>Get and set the octet at <code>index</code>. The values refer to individual bytes,
so the legal range is between <code>0x00</code> and <code>0xFF</code> hex or <code>0</code> and <code>255</code>.</p>
<p>Example: copy an ASCII string into a buffer, one byte at a time:</p>
<pre><code>str = "node.js";
buf = new Buffer(str.length);
for (var i = 0; i &lt; str.length ; i++) {
buf[i] = str.charCodeAt(i);
// node.js</code></pre>
<h3 id="buffer.isBuffer">Buffer.isBuffer(obj)</h3>
<p>Tests if <code>obj</code> is a <code>Buffer</code>.</p>
<h3 id="buffer.byteLength">Buffer.byteLength(string, encoding='utf8')</h3>
<p>Gives the actual byte length of a string. This is not the same as
<code>String.prototype.length</code> since that returns the number of <em>characters</em> in a
<pre><code>str = '\u00bd + \u00bc = \u00be';
console.log(str + ": " + str.length + " characters, " +
Buffer.byteLength(str, 'utf8') + " bytes");
// ½ + ¼ = ¾: 9 characters, 12 bytes</code></pre>
<h3 id="buffer.length">buffer.length</h3>
<p>The size of the buffer in bytes. Note that this is not necessarily the size
of the contents. <code>length</code> refers to the amount of memory allocated for the
buffer object. It does not change when the contents of the buffer are changed.</p>
<pre><code>buf = new Buffer(1234);
buf.write("some string", "ascii", 0);
// 1234
// 1234</code></pre>
<h3 id="buffer.copy">buffer.copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)</h3>
<p>Does a memcpy() between buffers.</p>
<p>Example: build two Buffers, then copy <code>buf1</code> from byte 16 through byte 19
into <code>buf2</code>, starting at the 8th byte in <code>buf2</code>.</p>
<pre><code>buf1 = new Buffer(26);
buf2 = new Buffer(26);
for (var i = 0 ; i &lt; 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
buf2[i] = 33; // ASCII !
buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// !!!!!!!!qrst!!!!!!!!!!!!!</code></pre>
<h3 id="buffer.slice">buffer.slice(start, end=buffer.length)</h3>
<p>Returns a new buffer which references the
same memory as the old, but offset and cropped by the <code>start</code> and <code>end</code>
<p><strong>Modifying the new buffer slice will modify memory in the original buffer!</strong></p>
<p>Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte
from the original Buffer.</p>
<pre><code>var buf1 = new Buffer(26);
for (var i = 0 ; i &lt; 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
var buf2 = buf1.slice(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
// abc
// !bc</code></pre>
<h2 id="streams">Streams</h2>
<p>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 <code>EventEmitter</code>.</p>
<h2 id="readable_Stream">Readable Stream</h2>
<p>A <code>Readable Stream</code> has the following methods, members, and events.</p>
<h3 id="event_data_">Event: 'data'</h3>
<p><code>function (data) { }</code></p>
<p>The <code>'data'</code> event emits either a <code>Buffer</code> (by default) or a string if
<code>setEncoding()</code> was used.</p>
<h3 id="event_end_">Event: 'end'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the stream has received an EOF (FIN in TCP terminology).
Indicates that no more <code>'data'</code> events will happen. If the stream is also
writable, it may be possible to continue writing.</p>
<h3 id="event_error_">Event: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>Emitted if there was an error receiving data.</p>
<h3 id="event_close_">Event: 'close'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the underlying file descriptor has been closed. Not all streams
will emit this. (For example, an incoming HTTP request will not emit
<h3 id="event_fd_">Event: 'fd'</h3>
<p><code>function (fd) { }</code></p>
<p>Emitted when a file descriptor is received on the stream. Only UNIX streams
support this functionality; all others will simply never emit this event.</p>
<h3 id="stream.readable">stream.readable</h3>
<p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an <code>'error'</code>
occurred, the stream came to an <code>'end'</code>, or <code>destroy()</code> was called.</p>
<h3 id="stream.setEncoding">stream.setEncoding(encoding)</h3>
<p>Makes the data event emit a string instead of a <code>Buffer</code>. <code>encoding</code> can be
<code>'utf8'</code>, <code>'ascii'</code>, or <code>'base64'</code>.</p>
<h3 id="stream.pause">stream.pause()</h3>
<p>Pauses the incoming <code>'data'</code> events.</p>
<h3 id="stream.resume">stream.resume()</h3>
<p>Resumes the incoming <code>'data'</code> events after a <code>pause()</code>.</p>
<h3 id="stream.destroy">stream.destroy()</h3>
<p>Closes the underlying file descriptor. Stream will not emit any more events.</p>
<h3 id="stream.destroySoon">stream.destroySoon()</h3>
<p>After the write queue is drained, close the file descriptor.</p>
<h3 id="stream.pipe">stream.pipe(destination, [options])</h3>
<p>This is a <code>Stream.prototype</code> method available on all <code>Stream</code>s.</p>
<p>Connects this read stream to <code>destination</code> WriteStream. Incoming
data on this stream gets written to <code>destination</code>. The destination and source
streams are kept in sync by pausing and resuming as necessary.</p>
<p>Emulating the Unix <code>cat</code> command:</p>
<p>By default <code>end()</code> is called on the destination when the source stream emits
<code>end</code>, so that <code>destination</code> is no longer writable. Pass <code>{ end: false }</code> as
<code>options</code> to keep the destination stream open.</p>
<p>This keeps <code>process.stdout</code> open so that "Goodbye" can be written at the end.</p>
process.stdin.pipe(process.stdout, { end: false });
process.stdin.on("end", function() {
<p>NOTE: If the source stream does not support <code>pause()</code> and <code>resume()</code>, this function
adds simple definitions which simply emit <code>'pause'</code> and <code>'resume'</code> events on
the source stream.</p>
<h2 id="writable_Stream">Writable Stream</h2>
<p>A <code>Writable Stream</code> has the following methods, members, and events.</p>
<h3 id="event_drain_">Event: 'drain'</h3>
<p><code>function () { }</code></p>
<p>Emitted after a <code>write()</code> method was called that returned <code>false</code> to
indicate that it is safe to write again.</p>
<h3 id="event_error_">Event: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>Emitted on error with the exception <code>exception</code>.</p>
<h3 id="event_close_">Event: 'close'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the underlying file descriptor has been closed.</p>
<h3 id="event_pipe_">Event: 'pipe'</h3>
<p><code>function (src) { }</code></p>
<p>Emitted when the stream is passed to a readable stream's pipe method.</p>
<h3 id="stream.writable">stream.writable</h3>
<p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an <code>'error'</code>
occurred or <code>end()</code> / <code>destroy()</code> was called.</p>
<h3 id="stream.write">stream.write(string, encoding='utf8', [fd])</h3>
<p>Writes <code>string</code> with the given <code>encoding</code> to the stream. Returns <code>true</code> if
the string has been flushed to the kernel buffer. Returns <code>false</code> to
indicate that the kernel buffer is full, and the data will be sent out in
the future. The <code>'drain'</code> event will indicate when the kernel buffer is
empty again. The <code>encoding</code> defaults to <code>'utf8'</code>.</p>
<p>If the optional <code>fd</code> parameter is specified, it is interpreted as an integral
file descriptor to be sent over the stream. This is only supported for UNIX
streams, and is silently ignored otherwise. When writing a file descriptor in
this manner, closing the descriptor before the stream drains risks sending an
invalid (closed) FD.</p>
<h3 id="stream.write">stream.write(buffer)</h3>
<p>Same as the above except with a raw buffer.</p>
<h3 id="stream.end">stream.end()</h3>
<p>Terminates the stream with EOF or FIN.</p>
<h3 id="stream.end">stream.end(string, encoding)</h3>
<p>Sends <code>string</code> with the given <code>encoding</code> and terminates the stream with EOF
or FIN. This is useful to reduce the number of packets sent.</p>
<h3 id="stream.end">stream.end(buffer)</h3>
<p>Same as above but with a <code>buffer</code>.</p>
<h3 id="stream.destroy">stream.destroy()</h3>
<p>Closes the underlying file descriptor. Stream will not emit any more events.</p>
<h3 id="stream.destroySoon">stream.destroySoon()</h3>
<p>After the write queue is drained, close the file descriptor. <code>destroySoon()</code>
can still destroy straight away, as long as there is no data left in the queue
for writes.</p>
<h2 id="crypto">Crypto</h2>
<p>Use <code>require('crypto')</code> to access this module.</p>
<p>The crypto module requires OpenSSL to be available on the underlying platform.
It offers a way of encapsulating secure credentials to be used as part
of a secure HTTPS net or http connection.</p>
<p>It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.</p>
<h3 id="crypto.createCredentials">crypto.createCredentials(details)</h3>
<p>Creates a credentials object, with the optional details being a dictionary with keys:</p>
<ul><li><code>key</code> : a string holding the PEM encoded private key</li><li><code>cert</code> : a string holding the PEM encoded certificate</li><li><code>ca</code> : either a string or list of strings of PEM encoded CA certificates to trust.</li></ul>
<p>If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in
<a href=""></a>.</p>
<h3 id="crypto.createHash">crypto.createHash(algorithm)</h3>
<p>Creates and returns a hash object, a cryptographic hash with the given algorithm
which can be used to generate hash digests.</p>
<p><code>algorithm</code> is dependent on the available algorithms supported by the version
of OpenSSL on the platform. Examples are <code>'sha1'</code>, <code>'md5'</code>, <code>'sha256'</code>, <code>'sha512'</code>, etc.
On recent releases, <code>openssl list-message-digest-algorithms</code> will display the available digest algorithms.</p>
<p>Example: this program that takes the sha1 sum of a file</p>
<pre><code>var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');
var shasum = crypto.createHash('sha1');
var s = fs.ReadStream(filename);
s.on('data', function(d) {
s.on('end', function() {
var d = shasum.digest('hex');
console.log(d + ' ' + filename);
<h3 id="hash.update">hash.update(data)</h3>
<p>Updates the hash content with the given <code>data</code>.
This can be called many times with new data as it is streamed.</p>
<h3 id="hash.digest">hash.digest(encoding='binary')</h3>
<p>Calculates the digest of all of the passed data to be hashed.
The <code>encoding</code> can be <code>'hex'</code>, <code>'binary'</code> or <code>'base64'</code>.</p>
<h3 id="crypto.createHmac">crypto.createHmac(algorithm, key)</h3>
<p>Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.</p>
<p><code>algorithm</code> is dependent on the available algorithms supported by OpenSSL - see createHash above.
<code>key</code> is the hmac key to be used.</p>
<h3 id="hmac.update">hmac.update(data)</h3>
<p>Update the hmac content with the given <code>data</code>.
This can be called many times with new data as it is streamed.</p>
<h3 id="hmac.digest">hmac.digest(encoding='binary')</h3>
<p>Calculates the digest of all of the passed data to the hmac.
The <code>encoding</code> can be <code>'hex'</code>, <code>'binary'</code> or <code>'base64'</code>.</p>
<h3 id="crypto.createCipher">crypto.createCipher(algorithm, key)</h3>
<p>Creates and returns a cipher object, with the given algorithm and key.</p>
<p><code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc.
On recent releases, <code>openssl list-cipher-algorithms</code> will display the available cipher algorithms.</p>
<h3 id="cipher.update">cipher.update(data, input_encoding='binary', output_encoding='binary')</h3>
<p>Updates the cipher with <code>data</code>, the encoding of which is given in <code>input_encoding</code>
and can be <code>'utf8'</code>, <code>'ascii'</code> or <code>'binary'</code>. The <code>output_encoding</code> specifies
the output format of the enciphered data, and can be <code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>.</p>
<p>Returns the enciphered contents, and can be called many times with new data as it is streamed.</p>
<h3 id="">'binary')</h3>
<p>Returns any remaining enciphered contents, with <code>output_encoding</code> being one of: <code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>.</p>
<h3 id="crypto.createDecipher">crypto.createDecipher(algorithm, key)</h3>
<p>Creates and returns a decipher object, with the given algorithm and key.
This is the mirror of the cipher object above.</p>
<h3 id="decipher.update">decipher.update(data, input_encoding='binary', output_encoding='binary')</h3>
<p>Updates the decipher with <code>data</code>, which is encoded in <code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>.
The <code>output_decoding</code> specifies in what format to return the deciphered plaintext: <code>'binary'</code>, <code>'ascii'</code> or <code>'utf8'</code>.</p>
<h3 id="">'binary')</h3>
<p>Returns any remaining plaintext which is deciphered,
with <code>output_encoding</code> being one of: <code>'binary'</code>, <code>'ascii'</code> or <code>'utf8'</code>.</p>
<h3 id="crypto.createSign">crypto.createSign(algorithm)</h3>
<p>Creates and returns a signing object, with the given algorithm.
On recent OpenSSL releases, <code>openssl list-public-key-algorithms</code> will display
the available signing algorithms. Examples are <code>'RSA-SHA256'</code>.</p>
<h3 id="signer.update">signer.update(data)</h3>
<p>Updates the signer object with data.
This can be called many times with new data as it is streamed.</p>
<h3 id="signer.sign">signer.sign(private_key, output_format='binary')</h3>
<p>Calculates the signature on all the updated data passed through the signer.
<code>private_key</code> is a string containing the PEM encoded private key for signing.</p>
<p>Returns the signature in <code>output_format</code> which can be <code>'binary'</code>, <code>'hex'</code> or <code>'base64'</code>.</p>
<h3 id="crypto.createVerify">crypto.createVerify(algorithm)</h3>
<p>Creates and returns a verification object, with the given algorithm.
This is the mirror of the signing object above.</p>
<h3 id="verifier.update">verifier.update(data)</h3>
<p>Updates the verifier object with data.
This can be called many times with new data as it is streamed.</p>
<h3 id="verifier.verify">verifier.verify(object, signature, signature_format='binary')</h3>
<p>Verifies the signed data by using the <code>object</code> and <code>signature</code>. <code>object</code> is a
string containing a PEM encoded object, which can be one of RSA public key,
DSA public key, or X.509 certificate. <code>signature</code> is the previously calculated
signature for the data, in the <code>signature_format</code> which can be <code>'binary'</code>,
<code>'hex'</code> or <code>'base64'</code>.</p>
<p>Returns true or false depending on the validity of the signature for the data and public key.</p>
<h2 id="tLS_">TLS (SSL)</h2>
<p>Use <code>require('tls')</code> to access this module.</p>
<p>The <code>tls</code> module uses OpenSSL to provide Transport Layer Security and/or
Secure Socket Layer: encrypted stream communication.</p>
<p>TLS/SSL is a public/private key infrastructure. Each client and each
server must have a private key. A private key is created like this</p>
<pre><code>openssl genrsa -out ryans-key.pem 1024</code></pre>
<p>All severs and some clients need to have a certificate. Certificates are public
keys signed by a Certificate Authority or self-signed. The first step to
getting a certificate is to create a "Certificate Signing Request" (CSR)
file. This is done with:</p>
<pre><code>openssl req -new -key ryans-key.pem -out ryans-csr.pem</code></pre>
<p>To create a self-signed certificate with the CSR, do this:</p>
<pre><code>openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem</code></pre>
<p>Alternatively you can send the CSR to a Certificate Authority for signing.</p>
<p>(TODO: docs on creating a CA, for now interested users should just look at
<code>test/fixtures/keys/Makefile</code> in the Node source code)</p>
<h3 id="s_tls.connect">s = tls.connect(port, [host], [options], callback)</h3>
<p>Creates a new client connection to the given <code>port</code> and <code>host</code>. (If <code>host</code>
defaults to <code>localhost</code>.) <code>options</code> should be an object which specifies</p>
<ul><li><p><code>key</code>: A string or <code>Buffer</code> containing the private key of the server in
PEM format. (Required)</p></li><li><p><code>cert</code>: A string or <code>Buffer</code> containing the certificate key of the server in
PEM format.</p></li><li><p><code>ca</code>: An array of strings or <code>Buffer</code>s of trusted certificates. If this is
omitted several well known "root" CAs will be used, like VeriSign.
These are used to authorize connections.</p></li></ul>
<p><code>tls.connect()</code> returns a cleartext <code>CryptoStream</code> object.</p>
<p>After the TLS/SSL handshake the <code>callback</code> is called. The <code>callback</code> will be
called no matter if the server's certificate was authorized or not. It is up
to the user to test <code>s.authorized</code> to see if the server certificate was
signed by one of the specified CAs. If <code>s.authorized === false</code> then the error
can be found in <code>s.authorizationError</code>.</p>
<h3 id="sTARTTLS">STARTTLS</h3>
<p>In the v0.4 branch no function exists for starting a TLS session on an
already existing TCP connection. This is possible it just requires a bit of
work. The technique is to use <code>tls.createSecurePair()</code> which returns two
streams: an encrypted stream and a plaintext stream. The encrypted stream is then
piped to the socket, the plaintext stream is what the user interacts with thereafter.</p>
<p><a href="">Here is some code that does it.</a></p>
<h3 id="tls.Server">tls.Server</h3>
<p>This class is a subclass of <code>net.Server</code> and has the same methods on it.
Instead of accepting just raw TCP connections, this accepts encrypted
connections using TLS or SSL.</p>
<p>Here is a simple example echo server:</p>
<pre><code>var tls = require('tls');
var fs = require('fs');
var options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem')
tls.createServer(options, function (s) {
<p>You can test this server by connecting to it with <code>openssl s_client</code>:</p>
<pre><code>openssl s_client -connect</code></pre>
<h4 id="tls.createServer">tls.createServer(options, secureConnectionListener)</h4>
<p>This is a constructor for the <code>tls.Server</code> class. The options object
has these possibilities:</p>
<ul><li><p><code>key</code>: A string or <code>Buffer</code> containing the private key of the server in
PEM format. (Required)</p></li><li><p><code>cert</code>: A string or <code>Buffer</code> containing the certificate key of the server in
PEM format. (Required)</p></li><li><p><code>ca</code>: An array of strings or <code>Buffer</code>s of trusted certificates. If this is
omitted several well known "root" CAs will be used, like VeriSign.
These are used to authorize connections.</p></li><li><p><code>requestCert</code>: If <code>true</code> the server will request a certificate from
clients that connect and attempt to verify that certificate. Default:
<code>false</code>.</p></li><li><p><code>rejectUnauthorized</code>: If <code>true</code> the server will reject any connection
which is not authorized with the list of supplied CAs. This option only
has an effect if <code>requestCert</code> is <code>true</code>. Default: <code>false</code>.</p></li></ul>
<h4 id="event_secureConnection_">Event: 'secureConnection'</h4>
<p><code>function (cleartextStream) {}</code></p>
<p>This event is emitted after a new connection has been successfully
handshaked. The argument is a duplex instance of <code>stream.Stream</code>. It has all
the common stream methods and events.</p>
<p><code>cleartextStream.authorized</code> is a boolean value which indicates if the
client has verified by one of the supplied certificate authorities for the
server. If <code>cleartextStream.authorized</code> is false, then
<code>cleartextStream.authorizationError</code> is set to describe how authorization
failed. Implied but worth mentioning: depending on the settings of the TLS
server, you unauthorized connections may be accepted.</p>
<h4 id="server.listen">server.listen(port, [host], [callback])</h4>
<p>Begin accepting connections on the specified <code>port</code> and <code>host</code>. If the
<code>host</code> is omitted, the server will accept connections directed to any
IPv4 address (<code>INADDR_ANY</code>).</p>
<p>This function is asynchronous. The last parameter <code>callback</code> will be called
when the server has been bound.</p>
<p>See <code>net.Server</code> for more information.</p>
<h4 id="server.close">server.close()</h4>
<p>Stops the server from accepting new connections. This function is
asynchronous, the server is finally closed when the server emits a <code>'close'</code>
<h4 id="server.maxConnections">server.maxConnections</h4>
<p>Set this property to reject connections when the server's connection count gets high.</p>
<h4 id="server.connections">server.connections</h4>
<p>The number of concurrent connections on the server.</p>
<h2 id="file_System">File System</h2>
<p>File I/O is provided by simple wrappers around standard POSIX functions. To
use this module do <code>require('fs')</code>. All the methods have asynchronous and
synchronous forms.</p>
<p>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 <code>null</code> or <code>undefined</code>.</p>
<p>Here is an example of the asynchronous version:</p>
<pre><code>var fs = require('fs');
fs.unlink('/tmp/hello', function (err) {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
<p>Here is the synchronous version:</p>
<pre><code>var fs = require('fs');
console.log('successfully deleted /tmp/hello');</code></pre>
<p>With the asynchronous methods there is no guaranteed ordering. So the
following is prone to error:</p>
<pre><code>fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
console.log('renamed complete');
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
<p>It could be that <code>fs.stat</code> is executed before <code>fs.rename</code>.
The correct way to do this is to chain the callbacks.</p>
<pre><code>fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
console.log('stats: ' + JSON.stringify(stats));
<p>In busy processes, the programmer is <em>strongly encouraged</em> to use the
asynchronous versions of these calls. The synchronous versions will block
the entire process until they complete--halting all connections.</p>
<p>Relative path to filename can be used, remember however that this path will be relative
to <code>process.cwd()</code>.</p>
<h3 id="fs.rename">fs.rename(path1, path2, [callback])</h3>
<p>Asynchronous rename(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.renameSync">fs.renameSync(path1, path2)</h3>
<p>Synchronous rename(2).</p>
<h3 id="fs.truncate">fs.truncate(fd, len, [callback])</h3>
<p>Asynchronous ftruncate(2). No arguments other than a possible exception are
given to the completion callback.</p>
<h3 id="fs.truncateSync">fs.truncateSync(fd, len)</h3>
<p>Synchronous ftruncate(2).</p>
<h3 id="fs.chown">fs.chown(path, mode, [callback])</h3>
<p>Asycnronous chown(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.chownSync">fs.chownSync(path, mode)</h3>
<p>Synchronous chown(2).</p>
<h3 id="fs.fchown">fs.fchown(path, mode, [callback])</h3>
<p>Asycnronous fchown(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.fchownSync">fs.fchownSync(path, mode)</h3>
<p>Synchronous fchown(2).</p>
<h3 id="fs.lchown">fs.lchown(path, mode, [callback])</h3>
<p>Asycnronous lchown(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.lchownSync">fs.lchownSync(path, mode)</h3>
<p>Synchronous lchown(2).</p>
<h3 id="fs.chmod">fs.chmod(path, mode, [callback])</h3>
<p>Asynchronous chmod(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.chmodSync">fs.chmodSync(path, mode)</h3>
<p>Synchronous chmod(2).</p>
<h3 id="fs.fchmod">fs.fchmod(fd, mode, [callback])</h3>
<p>Asynchronous fchmod(2). No arguments other than a possible exception
are given to the completion callback.</p>
<h3 id="fs.fchmodSync">fs.fchmodSync(path, mode)</h3>
<p>Synchronous fchmod(2).</p>
<h3 id="fs.lchmod">fs.lchmod(fd, mode, [callback])</h3>
<p>Asynchronous lchmod(2). No arguments other than a possible exception
are given to the completion callback.</p>
<h3 id="fs.lchmodSync">fs.lchmodSync(path, mode)</h3>
<p>Synchronous lchmod(2).</p>
<h3 id="fs.stat">fs.stat(path, [callback])</h3>
<p>Asynchronous stat(2). The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <a href="#fs.Stats">`fs.Stats`</a> object. It looks like this:</p>
<pre><code>{ dev: 2049,
ino: 305352,
mode: 16877,
nlink: 12,
uid: 1000,
gid: 1000,
rdev: 0,
size: 4096,
blksize: 4096,
blocks: 8,
atime: '2009-06-29T11:11:55Z',
mtime: '2009-06-29T11:11:40Z',
ctime: '2009-06-29T11:11:40Z' }</code></pre>
<p>See the <a href="#fs.Stats">fs.Stats</a> section below for more information.</p>
<h3 id="fs.lstat">fs.lstat(path, [callback])</h3>
<p>Asynchronous lstat(2). The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <code>fs.Stats</code> object. <code>lstat()</code> is identical to <code>stat()</code>, except that if
<code>path</code> is a symbolic link, then the link itself is stat-ed, not the file that it
refers to.</p>
<h3 id="fs.fstat">fs.fstat(fd, [callback])</h3>
<p>Asynchronous fstat(2). The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <code>fs.Stats</code> object. <code>fstat()</code> is identical to <code>stat()</code>, except that
the file to be stat-ed is specified by the file descriptor <code>fd</code>.</p>
<h3 id="fs.statSync">fs.statSync(path)</h3>
<p>Synchronous stat(2). Returns an instance of <code>fs.Stats</code>.</p>
<h3 id="fs.lstatSync">fs.lstatSync(path)</h3>
<p>Synchronous lstat(2). Returns an instance of <code>fs.Stats</code>.</p>
<h3 id="fs.fstatSync">fs.fstatSync(fd)</h3>
<p>Synchronous fstat(2). Returns an instance of <code>fs.Stats</code>.</p>
<h3 id="">, dstpath, [callback])</h3>
<p>Asynchronous link(2). No arguments other than a possible exception are given to
the completion callback.</p>
<h3 id="fs.linkSync">fs.linkSync(srcpath, dstpath)</h3>
<p>Synchronous link(2).</p>
<h3 id="fs.symlink">fs.symlink(linkdata, path, [callback])</h3>
<p>Asynchronous symlink(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.symlinkSync">fs.symlinkSync(linkdata, path)</h3>
<p>Synchronous symlink(2).</p>
<h3 id="fs.readlink">fs.readlink(path, [callback])</h3>
<p>Asynchronous readlink(2). The callback gets two arguments <code>(err,
<h3 id="fs.readlinkSync">fs.readlinkSync(path)</h3>
<p>Synchronous readlink(2). Returns the resolved path.</p>
<h3 id="fs.realpath">fs.realpath(path, [callback])</h3>
<p>Asynchronous realpath(2). The callback gets two arguments <code>(err,
<h3 id="fs.realpathSync">fs.realpathSync(path)</h3>
<p>Synchronous realpath(2). Returns the resolved path.</p>
<h3 id="fs.unlink">fs.unlink(path, [callback])</h3>
<p>Asynchronous unlink(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.unlinkSync">fs.unlinkSync(path)</h3>
<p>Synchronous unlink(2).</p>
<h3 id="fs.rmdir">fs.rmdir(path, [callback])</h3>
<p>Asynchronous rmdir(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.rmdirSync">fs.rmdirSync(path)</h3>
<p>Synchronous rmdir(2).</p>
<h3 id="fs.mkdir">fs.mkdir(path, mode, [callback])</h3>
<p>Asynchronous mkdir(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.mkdirSync">fs.mkdirSync(path, mode)</h3>
<p>Synchronous mkdir(2).</p>
<h3 id="fs.readdir">fs.readdir(path, [callback])</h3>
<p>Asynchronous readdir(3). Reads the contents of a directory.
The callback gets two arguments <code>(err, files)</code> where <code>files</code> is an array of
the names of the files in the directory excluding <code>'.'</code> and <code>'..'</code>.</p>
<h3 id="fs.readdirSync">fs.readdirSync(path)</h3>
<p>Synchronous readdir(3). Returns an array of filenames excluding <code>'.'</code> and
<h3 id="fs.close">fs.close(fd, [callback])</h3>
<p>Asynchronous close(2). No arguments other than a possible exception are given
to the completion callback.</p>
<h3 id="fs.closeSync">fs.closeSync(fd)</h3>
<p>Synchronous close(2).</p>
<h3 id="">, flags, [mode], [callback])</h3>
<p>Asynchronous file open. See open(2). <code>flags</code> can be:</p>
<ul><li><p><code>'r'</code> - Open file for reading.
An exception occurs if the file does not exist.</p></li><li><p><code>'r+'</code> - Open file for reading and writing.
An exception occurs if the file does not exist.</p></li><li><p><code>'w'</code> - Open file for writing.
The file is created (if it does not exist) or truncated (if it exists).</p></li><li><p><code>'w+'</code> - Open file for reading and writing.
The file is created (if it does not exist) or truncated (if it exists).</p></li><li><p><code>'a'</code> - Open file for appending.
The file is created if it does not exist.</p></li><li><p><code>'a+'</code> - Open file for reading and appending.
The file is created if it does not exist.</p></li></ul>
<p><code>mode</code> defaults to <code>0666</code>. The callback gets two arguments <code>(err, fd)</code>.</p>
<h3 id="fs.openSync">fs.openSync(path, flags, [mode])</h3>
<p>Synchronous open(2).</p>
<h3 id="fs.write">fs.write(fd, buffer, offset, length, position, [callback])</h3>
<p>Write <code>buffer</code> to the file specified by <code>fd</code>.</p>
<p><code>offset</code> and <code>length</code> determine the part of the buffer to be written.</p>
<p><code>position</code> refers to the offset from the beginning of the file where this data
should be written. If <code>position</code> is <code>null</code>, the data will be written at the
current position.
See pwrite(2).</p>
<p>The callback will be given three arguments <code>(err, written, buffer)</code> where <code>written</code>
specifies how many <em>bytes</em> were written into <code>buffer</code>.</p>
<p>Note that it is unsafe to use <code>fs.write</code> multiple times on the same file
without waiting for the callback. For this scenario,
<code>fs.createWriteStream</code> is strongly recommended.</p>
<h3 id="fs.writeSync">fs.writeSync(fd, buffer, offset, length, position)</h3>
<p>Synchronous version of buffer-based <code>fs.write()</code>. Returns the number of bytes
<h3 id="fs.writeSync">fs.writeSync(fd, str, position, encoding='utf8')</h3>
<p>Synchronous version of string-based <code>fs.write()</code>. Returns the number of bytes
<h3 id="">, buffer, offset, length, position, [callback])</h3>
<p>Read data from the file specified by <code>fd</code>.</p>
<p><code>buffer</code> is the buffer that the data will be written to.</p>
<p><code>offset</code> is offset within the buffer where writing will start.</p>
<p><code>length</code> is an integer specifying the number of bytes to read.</p>
<p><code>position</code> is an integer specifying where to begin reading from in the file.
If <code>position</code> is <code>null</code>, data will be read from the current file position.</p>
<p>The callback is given the three arguments, <code>(err, bytesRead, buffer)</code>.</p>
<h3 id="fs.readSync">fs.readSync(fd, buffer, offset, length, position)</h3>
<p>Synchronous version of buffer-based <code></code>. Returns the number of
<h3 id="fs.readSync">fs.readSync(fd, length, position, encoding)</h3>
<p>Synchronous version of string-based <code></code>. Returns the number of
<h3 id="fs.readFile">fs.readFile(filename, [encoding], [callback])</h3>
<p>Asynchronously reads the entire contents of a file. Example:</p>
<pre><code>fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
<p>The callback is passed two arguments <code>(err, data)</code>, where <code>data</code> is the
contents of the file.</p>
<p>If no encoding is specified, then the raw buffer is returned.</p>
<h3 id="fs.readFileSync">fs.readFileSync(filename, [encoding])</h3>
<p>Synchronous version of <code>fs.readFile</code>. Returns the contents of the <code>filename</code>.</p>
<p>If <code>encoding</code> is specified then this function returns a string. Otherwise it
returns a buffer.</p>
<h3 id="fs.writeFile">fs.writeFile(filename, data, encoding='utf8', [callback])</h3>
<p>Asynchronously writes data to a file, replacing the file if it already exists.
<code>data</code> can be a string or a buffer.</p>
<pre><code>fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
<h3 id="fs.writeFileSync">fs.writeFileSync(filename, data, encoding='utf8')</h3>
<p>The synchronous version of <code>fs.writeFile</code>.</p>
<h3 id="fs.watchFile">fs.watchFile(filename, [options], listener)</h3>
<p>Watch for changes on <code>filename</code>. The callback <code>listener</code> will be called each
time the file is accessed.</p>
<p>The second argument is optional. The <code>options</code> if provided should be an object
containing two members a boolean, <code>persistent</code>, and <code>interval</code>, a polling
value in milliseconds. The default is <code>{ persistent: true, interval: 0 }</code>.</p>
<p>The <code>listener</code> gets two arguments the current stat object and the previous
stat object:</p>
<pre><code>fs.watchFile(f, function (curr, prev) {
console.log('the current mtime is: ' + curr.mtime);
console.log('the previous mtime was: ' + prev.mtime);
<p>These stat objects are instances of <code>fs.Stat</code>.</p>
<p>If you want to be notified when the file was modified, not just accessed
you need to compare <code>curr.mtime</code> and `prev.mtime.</p>
<h3 id="fs.unwatchFile">fs.unwatchFile(filename)</h3>
<p>Stop watching for changes on <code>filename</code>.</p>
<h2 id="fs.Stats">fs.Stats</h2>
<p>Objects returned from <code>fs.stat()</code> and <code>fs.lstat()</code> are of this type.</p>
<ul><li><code>stats.isFile()</code></li><li><code>stats.isDirectory()</code></li><li><code>stats.isBlockDevice()</code></li><li><code>stats.isCharacterDevice()</code></li><li><code>stats.isSymbolicLink()</code> (only valid with <code>fs.lstat()</code>)</li><li><code>stats.isFIFO()</code></li><li><code>stats.isSocket()</code></li></ul>
<h2 id="fs.ReadStream">fs.ReadStream</h2>
<p><code>ReadStream</code> is a <code>Readable Stream</code>.</p>
<h3 id="event_open_">Event: 'open'</h3>
<p><code>function (fd) { }</code></p>
<p> <code>fd</code> is the file descriptor used by the ReadStream.</p>
<h3 id="fs.createReadStream">fs.createReadStream(path, [options])</h3>
<p>Returns a new ReadStream object (See <code>Readable Stream</code>).</p>
<p><code>options</code> is an object with the following defaults:</p>
<pre><code>{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
bufferSize: 64 * 1024
<p><code>options</code> can include <code>start</code> and <code>end</code> values to read a range of bytes from
the file instead of the entire file. Both <code>start</code> and <code>end</code> are inclusive and
start at 0.</p>
<p>An example to read the last 10 bytes of a file which is 100 bytes long:</p>
<pre><code>fs.createReadStream('sample.txt', {start: 90, end: 99});</code></pre>
<h2 id="fs.WriteStream">fs.WriteStream</h2>
<p><code>WriteStream</code> is a <code>Writable Stream</code>.</p>
<h3 id="event_open_">Event: 'open'</h3>
<p><code>function (fd) { }</code></p>
<p> <code>fd</code> is the file descriptor used by the WriteStream.</p>
<h3 id="fs.createWriteStream">fs.createWriteStream(path, [options])</h3>
<p>Returns a new WriteStream object (See <code>Writable Stream</code>).</p>
<p><code>options</code> is an object with the following defaults:</p>
<pre><code>{ flags: 'w',
encoding: null,
mode: 0666 }</code></pre>
<h2 id="path">Path</h2>
<p>This module contains utilities for dealing with file paths. Use
<code>require('path')</code> to use it. It provides the following methods:</p>
<h3 id="path.normalize">path.normalize(p)</h3>
<p>Normalize a string path, taking care of <code>'..'</code> and <code>'.'</code> parts.</p>
<p>When multiple slashes are found, they're replaces by a single one;
when the path contains a trailing slash, it is preserved.
On windows backslashes are used. </p>
// returns
<h3 id="path.join">path.join([path1], [path2], [...])</h3>
<p>Join all arguments together and normalize the resulting path.</p>
<pre><code>node&gt; require('path').join(
... '/foo', 'bar', 'baz/asdf', 'quux', '..')
<h3 id="path.resolve">path.resolve([from ...], to)</h3>
<p>Resolves <code>to</code> to an absolute path.</p>
<p>If <code>to</code> isn't already absolute <code>from</code> arguments are prepended in right to left
order, until an absolute path is found. If after using all <code>from</code> paths still
no absolute path is found, the current working directory is used as well. The
resulting path is normalized, and trailing slashes are removed unless the path
gets resolved to the root directory.</p>
<p>Another way to think of it is as a sequence of <code>cd</code> commands in a shell.</p>
<pre><code>path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')</code></pre>
<p>Is similar to:</p>
<pre><code>cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
<p>The difference is that the different paths don't need to exist and may also be
<pre><code>path.resolve('/foo/bar', './baz')
// returns
path.resolve('/foo/bar', '/tmp/file/')
// returns
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if currently in /home/myself/node, it returns
<h3 id="path.dirname">path.dirname(p)</h3>
<p>Return the directory name of a path. Similar to the Unix <code>dirname</code> command.</p>
// returns
<h3 id="path.basename">path.basename(p, [ext])</h3>
<p>Return the last portion of a path. Similar to the Unix <code>basename</code> command.</p>
// returns
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns
<h3 id="path.extname">path.extname(p)</h3>
<p>Return the extension of the path. Everything after the last '.' in the last portion
of the path. If there is no '.' in the last portion of the path or the only '.' is
the first character, then it returns an empty string. Examples:</p>
// returns
// returns
<h3 id="path.exists">path.exists(p, [callback])</h3>
<p>Test whether or not the given path exists. Then, call the <code>callback</code> argument
with either true or false. Example:</p>
<pre><code>path.exists('/etc/passwd', function (exists) {
util.debug(exists ? "it's there" : "no passwd!");
<h3 id="path.existsSync">path.existsSync(p)</h3>
<p>Synchronous version of <code>path.exists</code>.</p>
<h2 id="net">net</h2>
<p>The <code>net</code> module provides you with an asynchronous network wrapper. It contains
methods for creating both servers and clients (called streams). You can include
this module with <code>require("net");</code></p>
<h3 id="net.createServer">net.createServer([options], [connectionListener])</h3>
<p>Creates a new TCP server. The <code>connectionListener</code> argument is
automatically set as a listener for the <code>'connection'</code> event.</p>
<p><code>options</code> is an object with the following defaults:</p>
<pre><code>{ allowHalfOpen: false
<p>If <code>allowHalfOpen</code> is <code>true</code>, then the socket won't automatically send FIN
packet when the other end of the socket sends a FIN packet. The socket becomes
non-readable, but still writable. You should call the end() method explicitly.
See <code>'end'</code> event for more information.</p>
<h3 id="net.createConnection">net.createConnection(arguments...)</h3>
<p>Construct a new socket object and opens a socket to the given location. When
the socket is established the <code>'connect'</code> event will be emitted.</p>
<p>The arguments for this method change the type of connection:</p>
<ul><li><p><code>net.createConnection(port, [host])</code></p><p>Creates a TCP connection to <code>port</code> on <code>host</code>. If <code>host</code> is omitted, <code>localhost</code>
will be assumed.</p></li><li><p><code>net.createConnection(path)</code></p><p>Creates unix socket connection to <code>path</code></p></li></ul>
<hr />
<h3 id="net.Server">net.Server</h3>
<p>This class is used to create a TCP or UNIX server.</p>
<p>Here is an example of a echo server which listens for connections
on port 8124:</p>
<pre><code>var net = require('net');
var server = net.createServer(function (c) {
server.listen(8124, 'localhost');</code></pre>
<p>Test this by using <code>telnet</code>:</p>
<pre><code>telnet localhost 8124</code></pre>
<p>To listen on the socket <code>/tmp/echo.sock</code> the last line would just be
changed to</p>
<p>Use <code>nc</code> to connect to a UNIX domain socket server:</p>
<pre><code>nc -U /tmp/echo.sock</code></pre>
<p><code>net.Server</code> is an <code>EventEmitter</code> with the following events:</p>
<h4 id="server.listen">server.listen(port, [host], [callback])</h4>
<p>Begin accepting connections on the specified <code>port</code> and <code>host</code>. If the
<code>host</code> is omitted, the server will accept connections directed to any
IPv4 address (<code>INADDR_ANY</code>).</p>
<p>This function is asynchronous. The last parameter <code>callback</code> will be called
when the server has been bound.</p>
<p>One issue some users run into is getting <code>EADDRINUSE</code> errors. Meaning
another server is already running on the requested port. One way of handling this
would be to wait a second and the try again. This can be done with</p>
<pre><code>server.on('error', function (e) {
if (e.code == 'EADDRINUSE') {
console.log('Address in use, retrying...');
setTimeout(function () {
server.listen(PORT, HOST);
}, 1000);
<p>(Note: All sockets in Node are set SO_REUSEADDR already)</p>
<h4 id="server.listen">server.listen(path, [callback])</h4>
<p>Start a UNIX socket server listening for connections on the given <code>path</code>.</p>
<p>This function is asynchronous. The last parameter <code>callback</code> will be called
when the server has been bound.</p>
<h4 id="server.listenFD">server.listenFD(fd)</h4>
<p>Start a server listening for connections on the given file descriptor.</p>
<p>This file descriptor must have already had the <code>bind(2)</code> and <code>listen(2)</code> system
calls invoked on it. Additionally, it must be set non-blocking; try
<code>fcntl(fd, F_SETFL, O_NONBLOCK)</code>.</p>
<h4 id="server.pause">server.pause(msecs)</h4>
<p>Stop accepting connections for the given number of milliseconds (default is
one second). This could be useful for throttling new connections against
DoS attacks or other oversubscription.</p>
<h4 id="server.close">server.close()</h4>
<p>Stops the server from accepting new connections. This function is
asynchronous, the server is finally closed when the server emits a <code>'close'</code>
<h4 id="server.address">server.address()</h4>
<p>Returns the bound address and port of the server as reported by the operating system.
Useful to find which port was assigned when giving getting an OS-assigned address.
Returns an object with two properties, e.g. <code>{"address":"", "port":2121}</code></p>
<pre><code>var server = net.createServer(function (socket) {
// grab a random port.
server.listen(function() {
address = server.address();
console.log("opened server on %j", address);
<h4 id="server.maxConnections">server.maxConnections</h4>
<p>Set this property to reject connections when the server's connection count gets high.</p>
<h4 id="server.connections">server.connections</h4>
<p>The number of concurrent connections on the server.</p>
<h4 id="event_connection_">Event: 'connection'</h4>
<p><code>function (socket) {}</code></p>
<p>Emitted when a new connection is made. <code>socket</code> is an instance of
<h4 id="event_close_">Event: 'close'</h4>
<p><code>function () {}</code></p>
<p>Emitted when the server closes.</p>
<hr />
<h3 id="net.Socket">net.Socket</h3>
<p>This object is an abstraction of of a TCP or UNIX socket. <code>net.Socket</code>
instances implement a duplex Stream interface. They can be created by the
user and used as a client (with <code>connect()</code>) or they can be created by Node
and passed to the user through the <code>'connection'</code> event of a server.</p>
<p><code>net.Socket</code> instances are EventEmitters with the following events:</p>
<h4 id="new_net.Socket">new net.Socket([options])</h4>
<p>Construct a new socket object.</p>
<p><code>options</code> is an object with the following defaults:</p>
<pre><code>{ fd: null
type: null
allowHalfOpen: false
<p><code>fd</code> allows you to specify the existing file descriptor of socket. <code>type</code>
specified underlying protocol. It can be <code>'tcp4'</code>, <code>'tcp6'</code>, or <code>'unix'</code>.
About <code>allowHalfOpen</code>, refer to <code>createServer()</code> and <code>'end'</code> event.</p>
<h4 id="socket.connect">socket.connect(port, [host], [callback])</h4>
<h4 id="socket.connect">socket.connect(path, [callback])</h4>
<p>Opens the connection for a given socket. If <code>port</code> and <code>host</code> are given,
then the socket will be opened as a TCP socket, if <code>host</code> is omitted,
<code>localhost</code> will be assumed. If a <code>path</code> is given, the socket will be
opened as a unix socket to that path.</p>
<p>Normally this method is not needed, as <code>net.createConnection</code> opens the
socket. Use this only if you are implementing a custom Socket or if a
Socket is closed and you want to reuse it to connect to another server.</p>
<p>This function is asynchronous. When the <code>'connect'</code> event is emitted the
socket is established. If there is a problem connecting, the <code>'connect'</code>
event will not be emitted, the <code>'error'</code> event will be emitted with
the exception.</p>
<p>The <code>callback</code> parameter will be added as an listener for the 'connect'
<h4 id="socket.bufferSize">socket.bufferSize</h4>
<p><code>net.Socket</code> has the property that <code>socket.write()</code> always works. This is to
help users get up an running quickly. The computer cannot necessarily 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).</p>
<p>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 bytes to be
written, but the buffer may contain strings, and the strings are lazily
encoded, so the exact number of bytes is not known.)</p>
<p>Users who experience large or growing <code>bufferSize</code> should attempt to
"throttle" the data flows in their program with <code>pause()</code> and resume()`.</p>
<h4 id="socket.setEncoding">socket.setEncoding(encoding=null)</h4>
<p>Sets the encoding (either <code>'ascii'</code>, <code>'utf8'</code>, or <code>'base64'</code>) for data that is
<h4 id="socket.setSecure">socket.setSecure()</h4>
<p>This function has been removed in v0.3. It used to upgrade the connection to
SSL/TLS. See the <a href="tls.html#tLS_">TLS section</a> for the new API.</p>
<h4 id="socket.write">socket.write(data, [encoding], [callback])</h4>
<p>Sends data on the socket. The second parameter specifies the encoding in the
case of a string--it defaults to UTF8 encoding.</p>
<p>Returns <code>true</code> if the entire data was flushed successfully to the kernel
buffer. Returns <code>false</code> if all or part of the data was queued in user memory.
<code>'drain'</code> will be emitted when the buffer is again free.</p>
<p>The optional <code>callback</code> parameter will be executed when the data is finally
written out - this may not be immediately.</p>
<h4 id="socket.write">socket.write(data, [encoding], [fileDescriptor], [callback])</h4>
<p>For UNIX sockets, it is possible to send a file descriptor through the
socket. Simply add the <code>fileDescriptor</code> argument and listen for the <code>'fd'</code>
event on the other end.</p>
<h4 id="socket.end">socket.end([data], [encoding])</h4>
<p>Half-closes the socket. I.E., it sends a FIN packet. It is possible the
server will still send some data.</p>
<p>If <code>data</code> is specified, it is equivalent to calling <code>socket.write(data, encoding)</code>
followed by <code>socket.end()</code>.</p>
<h4 id="socket.destroy">socket.destroy()</h4>
<p>Ensures that no more I/O activity happens on this socket. Only necessary in
case of errors (parse error or so).</p>
<h4 id="socket.pause">socket.pause()</h4>
<p>Pauses the reading of data. That is, <code>'data'</code> events will not be emitted.
Useful to throttle back an upload.</p>
<h4 id="socket.resume">socket.resume()</h4>
<p>Resumes reading after a call to <code>pause()</code>.</p>
<h4 id="socket.setTimeout">socket.setTimeout(timeout, [callback])</h4>
<p>Sets the socket to timeout after <code>timeout</code> milliseconds of inactivity on
the socket. By default <code>net.Socket</code> do not have a timeout.</p>
<p>When an idle timeout is triggered the socket will receive a <code>'timeout'</code>
event but the connection will not be severed. The user must manually <code>end()</code>
or <code>destroy()</code> the socket.</p>
<p>If <code>timeout</code> is 0, then the existing idle timeout is disabled.</p>
<p>The optional <code>callback</code> parameter will be added as a one time listener for the <code>'timeout'</code> event.</p>
<h4 id="socket.setNoDelay">socket.setNoDelay(noDelay=true)</h4>
<p>Disables the Nagle algorithm. By default TCP connections use the Nagle
algorithm, they buffer data before sending it off. Setting <code>noDelay</code> will
immediately fire off data each time <code>socket.write()</code> is called.</p>
<h4 id="socket.setKeepAlive">socket.setKeepAlive(enable=false, [initialDelay])</h4>
<p>Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle socket.
Set <code>initialDelay</code> (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting 0 for
initialDelay will leave the value unchanged from the default
(or previous) setting.</p>
<h4 id="socket.address">socket.address()</h4>
<p>Returns the bound address and port of the socket as reported by the operating system.
Returns an object with two properties, e.g. <code>{"address":"", "port":62053}</code></p>
<h4 id="socket.remoteAddress">socket.remoteAddress</h4>
<p>The string representation of the remote IP address. For example,
<code>''</code> or <code>'2001:4860:a005::68'</code>.</p>
<p>This member is only present in server-side connections.</p>
<h4 id="event_connect_">Event: 'connect'</h4>
<p><code>function () { }</code></p>
<p>Emitted when a socket connection successfully is established.
See <code>connect()</code>.</p>
<h4 id="event_data_">Event: 'data'</h4>
<p><code>function (data) { }</code></p>
<p>Emitted when data is received. The argument <code>data</code> will be a <code>Buffer</code> or
<code>String</code>. Encoding of data is set by <code>socket.setEncoding()</code>.
(See the <a href="streams.html#readable_Stream">Readable Stream</a> section for more information.)</p>
<h4 id="event_end_">Event: 'end'</h4>
<p><code>function () { }</code></p>
<p>Emitted when the other end of the socket sends a FIN packet.</p>
<p>By default (<code>allowHalfOpen == false</code>) the socket will destroy its file
descriptor once it has written out its pending write queue. However, by
setting <code>allowHalfOpen == true</code> the socket will not automatically <code>end()</code>
its side allowing the user to write arbitrary amounts of data, with the
caveat that the user is required to <code>end()</code> their side now.</p>
<h4 id="event_timeout_">Event: 'timeout'</h4>
<p><code>function () { }</code></p>
<p>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.</p>
<p>See also: <code>socket.setTimeout()</code></p>
<h4 id="event_drain_">Event: 'drain'</h4>
<p><code>function () { }</code></p>
<p>Emitted when the write buffer becomes empty. Can be used to throttle uploads.</p>
<h4 id="event_error_">Event: 'error'</h4>
<p><code>function (exception) { }</code></p>
<p>Emitted when an error occurs. The <code>'close'</code> event will be called directly
following this event.</p>
<h4 id="event_close_">Event: 'close'</h4>
<p><code>function (had_error) { }</code></p>
<p>Emitted once the socket is fully closed. The argument <code>had_error</code> is a boolean
which says if the socket was closed due to a transmission error.</p>
<hr />
<h3 id="net.isIP">net.isIP</h3>
<h4 id="net.isIP">net.isIP(input)</h4>
<p>Tests if input is an IP address. Returns 0 for invalid strings,
returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.</p>
<h4 id="net.isIPv4">net.isIPv4(input)</h4>
<p>Returns true if input is a version 4 IP address, otherwise returns false.</p>
<h4 id="net.isIPv6">net.isIPv6(input)</h4>
<p>Returns true if input is a version 6 IP address, otherwise returns false.</p>
<h2 id="uDP_Datagram_Sockets">UDP / Datagram Sockets</h2>
<p>Datagram sockets are available through <code>require('dgram')</code>. Datagrams are most commonly
handled as IP/UDP messages but they can also be used over Unix domain sockets.</p>
<h3 id="event_message_">Event: 'message'</h3>
<p><code>function (msg, rinfo) { }</code></p>
<p>Emitted when a new datagram is available on a socket. <code>msg</code> is a <code>Buffer</code> and <code>rinfo</code> is
an object with the sender's address information and the number of bytes in the datagram.</p>
<h3 id="event_listening_">Event: 'listening'</h3>
<p><code>function () { }</code></p>
<p>Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
are created. Unix domain sockets do not start listening until calling <code>bind()</code> on them.</p>
<h3 id="event_close_">Event: 'close'</h3>
<p><code>function () { }</code></p>
<p>Emitted when a socket is closed with <code>close()</code>. No new <code>message</code> events will be emitted
on this socket.</p>
<h3 id="dgram.createSocket">dgram.createSocket(type, [callback])</h3>
<p>Creates a datagram socket of the specified types. Valid types are:
<code>udp4</code>, <code>udp6</code>, and <code>unix_dgram</code>.</p>
<p>Takes an optional callback which is added as a listener for <code>message</code> events.</p>
<h3 id="dgram.send">dgram.send(buf, offset, length, path, [callback])</h3>
<p>For Unix domain datagram sockets, the destination address is a pathname in the filesystem.
An optional callback may be supplied that is invoked after the <code>sendto</code> call is completed
by the OS. It is not safe to re-use <code>buf</code> until the callback is invoked. Note that
unless the socket is bound to a pathname with <code>bind()</code> there is no way to receive messages
on this socket.</p>
<p>Example of sending a message to syslogd on OSX via Unix domain socket <code>/var/run/syslog</code>:</p>
<pre><code>var dgram = require('dgram');
var message = new Buffer("A message to log.");
var client = dgram.createSocket("unix_dgram");
client.send(message, 0, message.length, "/var/run/syslog",
function (err, bytes) {
if (err) {
throw err;
console.log("Wrote " + bytes + " bytes to socket.");
<h3 id="dgram.send">dgram.send(buf, offset, length, port, address, [callback])</h3>
<p>For UDP sockets, the destination port and IP address must be specified. A string
may be supplied for the <code>address</code> parameter, and it will be resolved with DNS. An
optional callback may be specified to detect any DNS errors and when <code>buf</code> may be
re-used. Note that DNS lookups will delay the time that a send takes place, at
least until the next tick. The only way to know for sure that a send has taken place
is to use the callback.</p>
<p>Example of sending a UDP packet to a random port on <code>localhost</code>;</p>
<pre><code>var dgram = require('dgram');
var message = new Buffer("Some bytes");
var client = dgram.createSocket("udp4");
client.send(message, 0, message.length, 41234, "localhost");
<h3 id="dgram.bind">dgram.bind(path)</h3>
<p>For Unix domain datagram sockets, start listening for incoming datagrams on a
socket specified by <code>path</code>. Note that clients may <code>send()</code> without <code>bind()</code>,
but no datagrams will be received without a <code>bind()</code>.</p>
<p>Example of a Unix domain datagram server that echoes back all messages it receives:</p>
<pre><code>var dgram = require("dgram");
var serverPath = "/tmp/dgram_server_sock";
var server = dgram.createSocket("unix_dgram");
server.on("message", function (msg, rinfo) {
console.log("got: " + msg + " from " + rinfo.address);
server.send(msg, 0, msg.length, rinfo.address);
server.on("listening", function () {
console.log("server listening " + server.address().address);
<p>Example of a Unix domain datagram client that talks to this server:</p>
<pre><code>var dgram = require("dgram");
var serverPath = "/tmp/dgram_server_sock";
var clientPath = "/tmp/dgram_client_sock";
var message = new Buffer("A message at " + (new Date()));
var client = dgram.createSocket("unix_dgram");
client.on("message", function (msg, rinfo) {
console.log("got: " + msg + " from " + rinfo.address);
client.on("listening", function () {
console.log("client listening " + client.address().address);
client.send(message, 0, message.length, serverPath);
<h3 id="dgram.bind">dgram.bind(port, [address])</h3>
<p>For UDP sockets, listen for datagrams on a named <code>port</code> and optional <code>address</code>. If
<code>address</code> is not specified, the OS will try to listen on all addresses.</p>
<p>Example of a UDP server listening on port 41234:</p>
<pre><code>var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " +
rinfo.address + ":" + rinfo.port);
server.on("listening", function () {
var address = server.address();
console.log("server listening " +
address.address + ":" + address.port);
// server listening</code></pre>
<h3 id="dgram.close">dgram.close()</h3>
<p>Close the underlying socket and stop listening for data on it. UDP sockets
automatically listen for messages, even if they did not call <code>bind()</code>.</p>
<h3 id="dgram.address">dgram.address()</h3>
<p>Returns an object containing the address information for a socket. For UDP sockets,
this object will contain <code>address</code> and <code>port</code>. For Unix domain sockets, it will contain
only <code>address</code>.</p>
<h3 id="dgram.setBroadcast">dgram.setBroadcast(flag)</h3>
<p>Sets or clears the <code>SO_BROADCAST</code> socket option. When this option is set, UDP packets
may be sent to a local interface's broadcast address.</p>
<h3 id="dgram.setTTL">dgram.setTTL(ttl)</h3>
<p>Sets the <code>IP_TTL</code> socket option. TTL stands for "Time to Live," but in this context it
specifies the number of IP hops that a packet is allowed to go through. Each router or
gateway that forwards a packet decrements the TTL. If the TTL is decremented to 0 by a
router, it will not be forwarded. Changing TTL values is typically done for network
probes or when multicasting.</p>
<p>The argument to <code>setTTL()</code> is a number of hops between 1 and 255. The default on most
systems is 64.</p>
<h3 id="dgram.setMulticastTTL">dgram.setMulticastTTL(ttl)</h3>
<p>Sets the <code>IP_MULTICAST_TTL</code> socket option. TTL stands for "Time to Live," but in this
context it specifies the number of IP hops that a packet is allowed to go through,
specifically for multicast traffic. Each router or gateway that forwards a packet
decrements the TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.</p>
<p>The argument to <code>setMulticastTTL()</code> is a number of hops between 0 and 255. The default on most
systems is 64.</p>
<h3 id="dgram.setMulticastLoopback">dgram.setMulticastLoopback(flag)</h3>
<p>Sets or clears the <code>IP_MULTICAST_LOOP</code> socket option. When this option is set, multicast
packets will also be received on the local interface.</p>
<h3 id="dgram.addMembership">dgram.addMembership(multicastAddress, [multicastInterface])</h3>
<p>Tells the kernel to join a multicast group with <code>IP_ADD_MEMBERSHIP</code> socket option.</p>
<p>If <code>multicastInterface</code> is not specified, the OS will try to add membership to all valid
<h3 id="dgram.dropMembership">dgram.dropMembership(multicastAddress, [multicastInterface])</h3>
<p>Opposite of <code>addMembership</code> - tells the kernel to leave a multicast group with
<code>IP_DROP_MEMBERSHIP</code> socket option. This is automatically called by the kernel
when the socket is closed or process terminates, so most apps will never need to call
<p>If <code>multicastInterface</code> is not specified, the OS will try to drop membership to all valid
<h2 id="dNS">DNS</h2>
<p>Use <code>require('dns')</code> to access this module.</p>
<p>Here is an example which resolves <code>''</code> then reverse
resolves the IP addresses which are returned.</p>
<pre><code>var dns = require('dns');
dns.resolve4('', function (err, addresses) {
if (err) throw err;
console.log('addresses: ' + JSON.stringify(addresses));
addresses.forEach(function (a) {
dns.reverse(a, function (err, domains) {
if (err) {
console.log('reverse for ' + a + ' failed: ' +
} else {
console.log('reverse for ' + a + ': ' +
<h3 id="dns.lookup">dns.lookup(domain, family=null, callback)</h3>
<p>Resolves a domain (e.g. <code>''</code>) into the first found A (IPv4) or
AAAA (IPv6) record.</p>
<p>The callback has arguments <code>(err, address, family)</code>. The <code>address</code> argument
is a string representation of a IP v4 or v6 address. The <code>family</code> argument
is either the integer 4 or 6 and denotes the family of <code>address</code> (not
necessarily the value initially passed to <code>lookup</code>).</p>
<h3 id="dns.resolve">dns.resolve(domain, rrtype='A', callback)</h3>
<p>Resolves a domain (e.g. <code>''</code>) into an array of the record types
specified by rrtype. Valid rrtypes are <code>A</code> (IPV4 addresses), <code>AAAA</code> (IPV6
addresses), <code>MX</code> (mail exchange records), <code>TXT</code> (text records), <code>SRV</code> (SRV
records), <code>PTR</code> (used for reverse IP lookups), <code>NS</code> (name server records)
and <code>CNAME</code> (canonical name records).</p>
<p>The callback has arguments <code>(err, addresses)</code>. The type of each item
in <code>addresses</code> is determined by the record type, and described in the
documentation for the corresponding lookup methods below.</p>
<p>On error, <code>err</code> would be an instanceof <code>Error</code> object, where <code>err.errno</code> is
one of the error codes listed below and <code>err.message</code> is a string describing
the error in English.</p>
<h3 id="dns.resolve4">dns.resolve4(domain, callback)</h3>
<p>The same as <code>dns.resolve()</code>, but only for IPv4 queries (<code>A</code> records).
<code>addresses</code> is an array of IPv4 addresses (e.g.
<code>['', '', '']</code>).</p>
<h3 id="dns.resolve6">dns.resolve6(domain, callback)</h3>
<p>The same as <code>dns.resolve4()</code> except for IPv6 queries (an <code>AAAA</code> query).</p>
<h3 id="dns.resolveMx">dns.resolveMx(domain, callback)</h3>
<p>The same as <code>dns.resolve()</code>, but only for mail exchange queries (<code>MX</code> records).</p>
<p><code>addresses</code> is an array of MX records, each with a priority and an exchange
attribute (e.g. <code>[{'priority': 10, 'exchange': ''},...]</code>).</p>
<h3 id="dns.resolveTxt">dns.resolveTxt(domain, callback)</h3>
<p>The same as <code>dns.resolve()</code>, but only for text queries (<code>TXT</code> records).
<code>addresses</code> is an array of the text records available for <code>domain</code> (e.g.,
<code>['v=spf1 ip4: ~all']</code>).</p>
<h3 id="dns.resolveSrv">dns.resolveSrv(domain, callback)</h3>
<p>The same as <code>dns.resolve()</code>, but only for service records (<code>SRV</code> records).
<code>addresses</code> is an array of the SRV records available for <code>domain</code>. Properties
of SRV records are priority, weight, port, and name (e.g.,
<code>[{'priority': 10, {'weight': 5, 'port': 21223, 'name': ''}, ...]</code>).</p>
<h3 id="dns.reverse">dns.reverse(ip, callback)</h3>
<p>Reverse resolves an ip address to an array of domain names.</p>
<p>The callback has arguments <code>(err, domains)</code>.</p>
<h3 id="dns.resolveNs">dns.resolveNs(domain, callback)</h3>
<p>The same as <code>dns.resolve()</code>, but only for name server records (<code>NS</code> records).
<code>addresses</code> is an array of the name server records available for <code>domain</code>
(e.g., <code>['', '']</code>).</p>
<h3 id="dns.resolveCname">dns.resolveCname(domain, callback)</h3>
<p>The same as <code>dns.resolve()</code>, but only for canonical name records (<code>CNAME</code>
records). <code>addresses</code> is an array of the canonical name records available for
<code>domain</code> (e.g., <code>['']</code>).</p>
<p>If there an an error, <code>err</code> will be non-null and an instanceof the Error
<p>Each DNS query can return an error code.</p>
<ul><li><code>dns.TEMPFAIL</code>: timeout, SERVFAIL or similar.</li><li><code>dns.PROTOCOL</code>: got garbled reply.</li><li><code>dns.NXDOMAIN</code>: domain does not exists.</li><li><code>dns.NODATA</code>: domain exists but no data of reqd type.</li><li><code>dns.NOMEM</code>: out of memory while processing.</li><li><code>dns.BADQUERY</code>: the query is malformed.</li></ul>
<h2 id="hTTP">HTTP</h2>
<p>To use the HTTP server and client one must <code>require('http')</code>.</p>
<p>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.</p>
<p>HTTP message headers are represented by an object like this:</p>
<pre><code>{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive',
'accept': '*/*' }</code></pre>
<p>Keys are lowercased. Values are not modified.</p>
<p>In order to support the full spectrum of possible HTTP applications, Node's
HTTP API is very low-level. It deals with stream handling and message
parsing only. It parses a message into headers and body but it does not
parse the actual headers or the body.</p>
<h2 id="http.Server">http.Server</h2>
<p>This is an <code>EventEmitter</code> with the following events:</p>
<h3 id="event_request_">Event: 'request'</h3>
<p><code>function (request, response) { }</code></p>
<p>Emitted each time there is request. Note that there may be multiple requests
per connection (in the case of keep-alive connections).
<code>request</code> is an instance of <code>http.ServerRequest</code> and <code>response</code> is
an instance of <code>http.ServerResponse</code></p>
<h3 id="event_connection_">Event: 'connection'</h3>
<p><code>function (socket) { }</code></p>
<p> When a new TCP stream is established. <code>socket</code> is an object of type
<code>net.Socket</code>. Usually users will not want to access this event. The
<code>stream</code> can also be accessed at <code>request.connection</code>.</p>
<h3 id="event_close_">Event: 'close'</h3>
<p><code>function (errno) { }</code></p>
<p> Emitted when the server closes.</p>
<h3 id="event_checkContinue_">Event: 'checkContinue'</h3>
<p><code>function (request, response) { }</code></p>
<p>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.</p>
<p>Handling this event involves calling <code>response.writeContinue</code> if the client
should continue to send the request body, or generating an appropriate HTTP
response (e.g., 400 Bad Request) if the client should not continue to send the
request body.</p>
<p>Note that when this event is emitted and handled, the <code>request</code> event will
not be emitted.</p>
<h3 id="event_upgrade_">Event: 'upgrade'</h3>
<p><code>function (request, socket, head) { }</code></p>
<p>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
<ul><li><code>request</code> is the arguments for the http request, as it is in the request event.</li><li><code>socket</code> is the network socket between the server and client.</li><li><code>head</code> is an instance of Buffer, the first packet of the upgraded stream, this may be empty.</li></ul>
<p>After this event is emitted, the request's socket will not have a <code>data</code>
event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket.</p>
<h3 id="event_clientError_">Event: 'clientError'</h3>
<p><code>function (exception) { }</code></p>
<p>If a client connection emits an 'error' event - it will forwarded here.</p>
<h3 id="http.createServer">http.createServer([requestListener])</h3>
<p>Returns a new web server object.</p>
<p>The <code>requestListener</code> is a function which is automatically
added to the <code>'request'</code> event.</p>
<h3 id="server.listen">server.listen(port, [hostname], [callback])</h3>
<p>Begin accepting connections on the specified port and hostname. If the
hostname is omitted, the server will accept connections directed to any
IPv4 address (<code>INADDR_ANY</code>).</p>
<p>To listen to a unix socket, supply a filename instead of port and hostname.</p>
<p>This function is asynchronous. The last parameter <code>callback</code> will be called
when the server has been bound to the port.</p>
<h3 id="server.listen">server.listen(path, [callback])</h3>
<p>Start a UNIX socket server listening for connections on the given <code>path</code>.</p>
<p>This function is asynchronous. The last parameter <code>callback</code> will be called
when the server has been bound.</p>
<h3 id="server.close">server.close()</h3>
<p>Stops the server from accepting new connections.</p>
<h2 id="http.ServerRequest">http.ServerRequest</h2>
<p>This object is created internally by a HTTP server -- not by
the user -- and passed as the first argument to a <code>'request'</code> listener.</p>
<p>This is an <code>EventEmitter</code> with the following events:</p>
<h3 id="event_data_">Event: 'data'</h3>
<p><code>function (chunk) { }</code></p>
<p>Emitted when a piece of the message body is received.</p>
<p>Example: A chunk of the body is given as the single
argument. The transfer-encoding has been decoded. The
body chunk is a string. The body encoding is set with
<h3 id="event_end_">Event: 'end'</h3>
<p><code>function () { }</code></p>
<p>Emitted exactly once for each request. After that, no more <code>'data'</code> events
will be emitted on the request.</p>
<h3 id="event_close_">Event: 'close'</h3>
<p><code>function (err) { }</code></p>
<p>Indicates that the underlaying connection was terminated before
<code>response.end()</code> was called or able to flush.</p>
<p>The <code>err</code> parameter is always present and indicates the reason for the timeout:</p>
<p><code>err.code === 'timeout'</code> indicates that the underlaying connection timed out.
This may happen because all incoming connections have a default timeout of 2
<p><code>err.code === 'aborted'</code> means that the client has closed the underlaying
connection prematurely.</p>
<p>Just like <code>'end'</code>, this event occurs only once per request, and no more <code>'data'</code>
events will fire afterwards.</p>
<p>Note: <code>'close'</code> can fire after <code>'end'</code>, but not vice versa.</p>
<h3 id="request.method">request.method</h3>
<p>The request method as a string. Read only. Example:
<code>'GET'</code>, <code>'DELETE'</code>.</p>
<h3 id="request.url">request.url</h3>
<p>Request URL string. This contains only the URL that is
present in the actual HTTP request. If the request is:</p>
<pre><code>GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
<p>Then <code>request.url</code> will be:</p>
<p>If you would like to parse the URL into its parts, you can use
<code>require('url').parse(request.url)</code>. Example:</p>
<pre><code>node&gt; require('url').parse('/status?name=ryan')
{ href: '/status?name=ryan',
search: '?name=ryan',
query: 'name=ryan',
pathname: '/status' }</code></pre>
<p>If you would like to extract the params from the query string,
you can use the <code>require('querystring').parse</code> function, or pass
<code>true</code> as the second argument to <code>require('url').parse</code>. Example:</p>
<pre><code>node&gt; require('url').parse('/status?name=ryan', true)
{ href: '/status?name=ryan',
search: '?name=ryan',
query: { name: 'ryan' },
pathname: '/status' }</code></pre>
<h3 id="request.headers">request.headers</h3>
<p>Read only.</p>
<h3 id="request.trailers">request.trailers</h3>
<p>Read only; HTTP trailers (if present). Only populated after the 'end' event.</p>
<h3 id="request.httpVersion">request.httpVersion</h3>
<p>The HTTP protocol version as a string. Read only. Examples:
<code>'1.1'</code>, <code>'1.0'</code>.
Also <code>request.httpVersionMajor</code> is the first integer and
<code>request.httpVersionMinor</code> is the second.</p>
<h3 id="request.setEncoding">request.setEncoding(encoding=null)</h3>
<p>Set the encoding for the request body. Either <code>'utf8'</code> or <code>'binary'</code>. Defaults
to <code>null</code>, which means that the <code>'data'</code> event will emit a <code>Buffer</code> object..</p>
<h3 id="request.pause">request.pause()</h3>
<p>Pauses request from emitting events. Useful to throttle back an upload.</p>
<h3 id="request.resume">request.resume()</h3>
<p>Resumes a paused request.</p>
<h3 id="request.connection">request.connection</h3>
<p>The <code>net.Socket</code> object associated with the connection.</p>
<p>With HTTPS support, use request.connection.verifyPeer() and
request.connection.getPeerCertificate() to obtain the client's
authentication details.</p>
<h2 id="http.ServerResponse">http.ServerResponse</h2>
<p>This object is created internally by a HTTP server--not by the user. It is
passed as the second parameter to the <code>'request'</code> event. It is a <code>Writable Stream</code>.</p>
<h3 id="response.writeContinue">response.writeContinue()</h3>
<p>Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the <a href="#event_checkContinue_">checkContinue</a> event on
<h3 id="response.writeHead">response.writeHead(statusCode, [reasonPhrase], [headers])</h3>
<p>Sends a response header to the request. The status code is a 3-digit HTTP
status code, like <code>404</code>. The last argument, <code>headers</code>, are the response headers.
Optionally one can give a human-readable <code>reasonPhrase</code> as the second
<pre><code>var body = 'hello world';
response.writeHead(200, {
'Content-Length': body.length,
'Content-Type': 'text/plain' });</code></pre>
<p>This method must only be called once on a message and it must
be called before <code>response.end()</code> is called.</p>
<p>If you call <code>response.write()</code> or <code>response.end()</code> before calling this, the
implicit/mutable headers will be calculated and call this function for you.</p>
<p>Note: that Content-Length is given in bytes not characters. The above example
works because the string <code>'hello world'</code> contains only single byte characters.
If the body contains higher coded characters then <code>Buffer.byteLength()</code>
should be used to determine the number of bytes in a given encoding.</p>
<h3 id="response.statusCode">response.statusCode</h3>
<p>When using implicit headers (not calling <code>response.writeHead()</code> explicitly), this property
controls the status code that will be send to the client when the headers get
<pre><code>response.statusCode = 404;</code></pre>
<h3 id="response.setHeader">response.setHeader(name, value)</h3>
<p>Sets a single header value for implicit headers. If this header already exists
in the to-be-sent headers, it's value will be replaced. Use an array of strings
here if you need to send multiple headers with the same name.</p>
<pre><code>response.setHeader("Content-Type", "text/html");</code></pre>
<pre><code>response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);</code></pre>
<h3 id="response.getHeader">response.getHeader(name)</h3>
<p>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.</p>
<pre><code>var contentType = response.getHeader('content-type');</code></pre>
<h3 id="response.removeHeader">response.removeHeader(name)</h3>
<p>Removes a header that's queued for implicit sending.</p>
<h3 id="response.write">response.write(chunk, encoding='utf8')</h3>
<p>If this method is called and <code>response.writeHead()</code> has not been called, it will
switch to implicit header mode and flush the implicit headers.</p>
<p>This sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.</p>
<p><code>chunk</code> can be a string or a buffer. If <code>chunk</code> is a string,
the second parameter specifies how to encode it into a byte stream.
By default the <code>encoding</code> is <code>'utf8'</code>.</p>
<p><strong>Note</strong>: This is the raw HTTP body and has nothing to do with
higher-level multi-part body encodings that may be used.</p>
<p>The first time <code>response.write()</code> is called, it will send the buffered
header information and the first body to the client. The second time
<code>response.write()</code> is called, Node assumes you're going to be streaming
data, and sends that separately. That is, the response is buffered up to the
first chunk of body.</p>
<h3 id="response.addTrailers">response.addTrailers(headers)</h3>
<p>This method adds HTTP trailing headers (a header but at the end of the
message) to the response.</p>
<p>Trailers will <strong>only</strong> 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.</p>
<p>Note that HTTP requires the <code>Trailer</code> header to be sent if you intend to
emit trailers, with a list of the header fields in its value. E.g.,</p>
<pre><code>response.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'TraceInfo' });
response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
<h3 id="response.end">response.end([data], [encoding])</h3>
<p>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, <code>response.end()</code>, MUST be called on each
<p>If <code>data</code> is specified, it is equivalent to calling <code>response.write(data, encoding)</code>
followed by <code>response.end()</code>.</p>
<h2 id="http.request">http.request(options, callback)</h2>
<p>Node maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.</p>
<ul><li><code>host</code>: A domain name or IP address of the server to issue the request to.</li><li><code>port</code>: Port of remote server.</li><li><code>method</code>: A string specifying the HTTP request method. Possible values:
<code>'GET'</code> (default), <code>'POST'</code>, <code>'PUT'</code>, and <code>'DELETE'</code>.</li><li><code>path</code>: Request path. Should include query string and fragments if any.
E.G. <code>'/index.html?page=12'</code></li><li><code>headers</code>: An object containing request headers.</li><li><code>agent</code>: Controls <code>Agent</code> behavior. Possible values:<ul><li><code>undefined</code> (default): use default <code>Agent</code> for this host and port.</li><li><code>Agent</code> object: explicitly use the passed in <code>Agent</code>.</li><li><code>false</code>: explicitly generate a new <code>Agent</code> for this host and port. <code>Agent</code> will not be re-used.</li></ul></li></ul>
<p><code>http.request()</code> returns an instance of the <code>http.ClientRequest</code>
class. The <code>ClientRequest</code> instance is a writable stream. If one needs to
upload a file with a POST request, then write to the <code>ClientRequest</code> object.</p>
<pre><code>var options = {
host: '',
port: 80,
path: '/upload',
method: 'POST'
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
// write data to request body
<p>Note that in the example <code>req.end()</code> was called. With <code>http.request()</code> one
must always call <code>req.end()</code> to signify that you're done with the request -
even if there is no data being written to the request body.</p>
<p>If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an <code>'error'</code> event is emitted
on the returned request object.</p>
<p>There are a few special headers that should be noted.</p>
<ul><li><p>Sending a 'Connection: keep-alive' will notify Node that the connection to
the server should be persisted until the next request.</p></li><li><p>Sending a 'Content-length' header will disable the default chunked encoding.</p></li><li><p>Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', you should both set a timeout
and listen for the <code>continue</code> event. See RFC2616 Section 8.2.3 for more
<h2 id="http.get">http.get(options, callback)</h2>
<p>Since most requests are GET requests without bodies, Node provides this
convenience method. The only difference between this method and <code>http.request()</code> is
that it sets the method to GET and calls <code>req.end()</code> automatically.</p>
<pre><code>var options = {
host: '',
port: 80,
path: '/index.html'
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
<h2 id="http.Agent">http.Agent</h2>
<h2 id="http.getAgent">http.getAgent(host, port)</h2>
<p><code>http.request()</code> uses a special <code>Agent</code> for managing multiple connections to
an HTTP server. Normally <code>Agent</code> instances should not be exposed to user
code, however in certain situations it's useful to check the status of the
agent. The <code>http.getAgent()</code> function allows you to access the agents.</p>
<h3 id="event_upgrade_">Event: 'upgrade'</h3>
<p><code>function (response, socket, head) { }</code></p>
<p>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.</p>
<p>A client server pair that show you how to listen for the <code>upgrade</code> event using <code>http.getAgent</code>:</p>
<pre><code>var http = require('http');
var net = require('net');
// Create an HTTP server
var srv = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
srv.on('upgrade', function(req, socket, upgradeHead) {
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
socket.ondata = function(data, start, end) {
socket.write(data.toString('utf8', start, end), 'utf8'); // echo back
// now that server is running
srv.listen(1337, '', function() {
// make a request
var agent = http.getAgent('', 1337);
var options = {
agent: agent,
port: 1337,
host: '',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
var req = http.request(options);
agent.on('upgrade', function(res, socket, upgradeHead) {
console.log('got upgraded!');
<h3 id="agent.maxSockets">agent.maxSockets</h3>
<p>By default set to 5. Determines how many concurrent sockets the agent can have open.</p>