Sie sind auf Seite 1von 88

Node.js Manual & Documentation

Index | View on single page

Table Of Contents

SynopsisIndex | View on single page Table Of Contents Global Objects global process require() require.resolve()

Global ObjectsIndex | View on single page Table Of Contents Synopsis global process require() require.resolve() require.paths

globalon single page Table Of Contents Synopsis Global Objects process require() require.resolve() require.paths filename

processsingle page Table Of Contents Synopsis Global Objects global require() require.resolve() require.paths filename dirname

require()Table Of Contents Synopsis Global Objects global process require.resolve() require.paths filename dirname module

require.resolve()Of Contents Synopsis Global Objects global process require() require.paths filename dirname module Timers

require.paths filename filename

process require() require.resolve() require.paths filename dirname module Timers setTimeout(callback, delay, [arg], [

dirname

modulerequire() require.resolve() require.paths filename dirname Timers setTimeout(callback, delay, [arg], [ ])

Timersrequire.resolve() require.paths filename dirname module setTimeout(callback, delay, [arg], [ ])

setTimeout(callback, delay, [arg], [])

])

clearTimeout(timeoutId) 

 

setInterval(callback, delay, [arg], [])

])

clearInterval(intervalId)  setInterval(callback, delay, [arg], [ ]) Standard Modules Modules Module Resolving Addons process

Standard Modulesdelay, [arg], [ ]) clearInterval(intervalId) Modules Module Resolving Addons process Event:

Modules[arg], [ ]) clearInterval(intervalId) Standard Modules Module Resolving Addons process Event: 'exit' Event:

Module Resolving[ ]) clearInterval(intervalId) Standard Modules Modules Addons process Event: 'exit' Event:

AddonsStandard Modules Modules Module Resolving process Event: 'exit' Event:

processStandard Modules Modules Module Resolving Addons Event: 'exit' Event: 'uncaughtException'

Event: 'exit'Standard Modules Modules Module Resolving Addons process Event: 'uncaughtException' Signal Events

Event: 'uncaughtException'Module Resolving Addons process Event: 'exit' Signal Events process.stdout process.stdin process.argv

Signal EventsEvent: 'exit' Event: 'uncaughtException' process.stdout process.stdin process.argv process.execPath

process.stdoutEvent: 'uncaughtException' Signal Events process.stdin process.argv process.execPath

process.stdin'uncaughtException' Signal Events process.stdout process.argv process.execPath process.chdir(directory)

process.argvSignal Events process.stdout process.stdin process.execPath process.chdir(directory) process.cwd()

process.execPathSignal Events process.stdout process.stdin process.argv process.chdir(directory) process.cwd() process.env

process.chdir(directory)process.stdout process.stdin process.argv process.execPath process.cwd() process.env process.exit(code=0)

process.cwd()process.argv process.execPath process.chdir(directory) process.env process.exit(code=0) process.getgid()

process.envprocess.execPath process.chdir(directory) process.cwd() process.exit(code=0) process.getgid() process.setgid(id)

process.exit(code=0)process.argv process.execPath process.chdir(directory) process.cwd() process.env process.getgid() process.setgid(id)

process.getgid()process.argv process.execPath process.chdir(directory) process.cwd() process.env process.exit(code=0) process.setgid(id)

process.setgid(id)process.argv process.execPath process.chdir(directory) process.cwd() process.env process.exit(code=0) process.getgid()

process.getuid()process.setuid(id) process.version process.installPrefix process.kill(pid, signal='SIGINT') process.pid

process.setuid(id)process.getuid() process.version process.installPrefix process.kill(pid, signal='SIGINT') process.pid

process.versionprocess.getuid() process.setuid(id) process.installPrefix process.kill(pid, signal='SIGINT') process.pid

process.installPrefixprocess.getuid() process.setuid(id) process.version process.kill(pid, signal='SIGINT') process.pid process.title

process.kill(pid, signal='SIGINT')process.setuid(id) process.version process.installPrefix process.pid process.title process.platform

process.pidprocess.kill(pid, signal='SIGINT') process.title process.platform process.memoryUsage()

process.titleprocess.kill(pid, signal='SIGINT') process.pid process.platform process.memoryUsage()

process.platformsignal='SIGINT') process.pid process.title process.memoryUsage() process.nextTick(callback)

process.memoryUsage() process.nextTick(callback)process.pid process.title process.platform process.umask([mask]) util util.debug(string)

process.umask([mask])process.memoryUsage() process.nextTick(callback) util util.debug(string) util.log(string)

utilprocess.nextTick(callback) process.umask([mask]) util.debug(string) util.log(string) util.inspect(object,

util.debug(string)process.nextTick(callback) process.umask([mask]) util util.log(string) util.inspect(object, showHidden=false,

util.log(string)process.umask([mask]) util util.debug(string) util.inspect(object, showHidden=false, depth=2)

util.inspect(object, showHidden=false, depth=2)util util.debug(string) util.log(string) util.pump(readableStream, writeableStream, [callback])

util.pump(readableStream, writeableStream, [callback])

util.inherits(constructor, superConstructor)util.pump(readableStream, writeableStream, [callback]) Events events.EventEmitter emitter.addListener(event,

Events[callback]) util.inherits(constructor, superConstructor) events.EventEmitter emitter.addListener(event, listener)

events.EventEmitter emitter.addListener(event, listener)util.inherits(constructor, superConstructor) Events emitter.on(event, listener) emitter.once(event, listener)

emitter.on(event, listener)events.EventEmitter emitter.addListener(event, listener) emitter.once(event, listener) emitter.removeListener(event,

emitter.once(event, listener) emitter.removeListener(event, listener) emitter.removeAllListeners(event)listener) emitter.on(event, listener) emitter.listeners(event) emitter.emit(event, [arg1], [arg2],

emitter.listeners(event)listener) emitter.removeAllListeners(event) emitter.emit(event, [arg1], [arg2], [ Event:

emitter.emit(event, [arg1], [arg2], [emitter.removeAllListeners(event) emitter.listeners(event) Event: 'newListener' ]) Buffers new Buffer(size) new

Event: 'newListener'emitter.emit(event, [arg1], [arg2], [ ]) Buffers new Buffer(size) new Buffer(array) new

])

Buffers[arg1], [arg2], [ Event: 'newListener' ]) new Buffer(size) new Buffer(array) new Buffer(str,

new Buffer(size)[arg1], [arg2], [ Event: 'newListener' ]) Buffers new Buffer(array) new Buffer(str, encoding='utf8')

new Buffer(array)[ Event: 'newListener' ]) Buffers new Buffer(size) new Buffer(str, encoding='utf8')

new Buffer(str, encoding='utf8')]) Buffers new Buffer(size) new Buffer(array) buffer.write(string, offset=0, encoding='utf8')

buffer.write(string, offset=0, encoding='utf8')new Buffer(array) new Buffer(str, encoding='utf8') buffer.toString(encoding, start=0, end=buffer.length)

buffer.toString(encoding, start=0, end=buffer.length)buffer.write(string, offset=0, encoding='utf8') buffer[index] Buffer.isBuffer(obj) Buffer.byteLength(string,

buffer[index]buffer.toString(encoding, start=0, end=buffer.length) Buffer.isBuffer(obj) Buffer.byteLength(string,

Buffer.isBuffer(obj)start=0, end=buffer.length) buffer[index] Buffer.byteLength(string, encoding='utf8')

Buffer.byteLength(string, encoding='utf8')end=buffer.length) buffer[index] Buffer.isBuffer(obj) buffer.length buffer.copy(targetBuffer, targetStart=0,

buffer.lengthBuffer.byteLength(string, encoding='utf8') buffer.copy(targetBuffer, targetStart=0, sourceStart=0,

buffer.copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)encoding='utf8') buffer.length buffer.slice(start, end=buffer.length) Streams Readable

buffer.slice(start, end=buffer.length)targetStart=0, sourceStart=0, sourceEnd=buffer.length) Streams Readable Stream Event: 'data' Event:

Streamsbuffer.slice(start, end=buffer.length) Readable Stream Event: 'data' Event: 'end'

Readable Streambuffer.slice(start, end=buffer.length) Streams Event: 'data' Event: 'end' Event:

Event: 'data'end=buffer.length) Streams Readable Stream Event: 'end' Event: 'error' Event:

Event: 'end'Streams Readable Stream Event: 'data' Event: 'error' Event: 'close' Event:

Event: 'error'Readable Stream Event: 'data' Event: 'end' Event: 'close' Event: 'fd' stream.readable

Event: 'close''data' Event: 'end' Event: 'error' Event: 'fd' stream.readable

Event: 'fd'Event: 'end' Event: 'error' Event: 'close' stream.readable stream.setEncoding(encoding)

stream.readable stream.setEncoding(encoding)Stream Event: 'data' Event: 'end' Event: 'error' Event: 'close' Event: 'fd'

stream.pause()

stream.pause()

stream.resume()

stream.resume()

stream.destroy()

stream.destroy()

stream.pipe(destination, [options])

stream.pipe(destination, [options])

Writable Stream Event: 'drain' Event: 'error' Event: 'close' stream.writeable stream.write(string, encoding='utf8', [fd]) stream.write(buffer) stream.end() stream.end(string, encoding) stream.end(buffer) stream.destroy()stream.destroy() stream.pipe(destination, [options]) Crypto crypto.createCredentials(details)

Crypto crypto.createCredentials(details) crypto.createHash(algorithm) hash.update(data) hash.digest(encoding='binary') crypto.createHmac(algorithm, key) hmac.update(data) hmac.digest(encoding='binary') crypto.createCipher(algorithm, key) cipher.update(data, input_encoding='binary', output_encoding='binary') cipher.final(output_encoding='binary') crypto.createDecipher(algorithm, key) decipher.update(data, input_encoding='binary', output_encoding='binary') decipher.final(output_encoding='binary') crypto.createSign(algorithm) signer.update(data) signer.sign(private_key, output_format='binary') crypto.createVerify(algorithm) verifier.update(data) verifier.verify(public_key, signature, signature_format='binary')encoding) stream.end(buffer) stream.destroy() TLS (SSL) s = tls.connect(port, [host], [options], callback)

TLS (SSL) s = tls.connect(port, [host], [options], callback) tls.Server tls.createServer(options, secureConnectionListener)signature, signature_format='binary') Event: 'secureConnection' server.listen(port,

tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
tls.createServer(options, secureConnectionListener) Event: 'secureConnection' server.listen(port,
Event: 'secureConnection'

Event: 'secureConnection'

Event: 'secureConnection'
Event: 'secureConnection'
Event: 'secureConnection'
Event: 'secureConnection'

server.listen(port, [host], [callback])

server.close()

server.maxConnections

server.connections

File System fs.rename(path1, path2, [callback]) fs.renameSync(path1, path2)server.listen(port, [host], [callback]) server.close() server.maxConnections server.connections

server.maxConnections server.connections File System fs.rename(path1, path2, [callback]) fs.renameSync(path1, path2)
server.maxConnections server.connections File System fs.rename(path1, path2, [callback]) fs.renameSync(path1, path2)
fs.truncate(fd, len, [callback]) fs.truncateSync(fd, len) fs.chmod(path, mode, [callback]) fs.chmodSync(path, mode)
fs.truncate(fd, len, [callback])
fs.truncateSync(fd, len)
fs.chmod(path, mode, [callback])
fs.chmodSync(path, mode)
fs.stat(path, [callback])
fs.lstat(path, [callback])
fs.fstat(fd, [callback])
fs.statSync(path)
fs.lstatSync(path)
fs.fstatSync(fd)
fs.link(srcpath, dstpath, [callback])
fs.linkSync(dstpath, srcpath)
fs.symlink(linkdata, path, [callback])
fs.symlinkSync(linkdata, path)
fs.readlink(path, [callback])
fs.readlinkSync(path)
fs.realpath(path, [callback])
fs.realpathSync(path)
fs.unlink(path, [callback])
fs.unlinkSync(path)
fs.rmdir(path, [callback])
fs.rmdirSync(path)
fs.mkdir(path, mode, [callback])
fs.mkdirSync(path, mode)
fs.readdir(path, [callback])
fs.readdirSync(path)
fs.close(fd, [callback])
fs.closeSync(fd)
fs.open(path, flags, mode=0666, [callback])
fs.openSync(path, flags, mode=0666)
fs.write(fd, buffer, offset, length, position, [callback])
fs.writeSync(fd, buffer, offset, length, position)
fs.writeSync(fd, str, position, encoding='utf8')
fs.read(fd, buffer, offset, length, position, [callback])
fs.readSync(fd, buffer, offset, length, position)
fs.readSync(fd, length, position, encoding)
fs.readFile(filename, [encoding], [callback])
fs.readFileSync(filename, [encoding])
fs.writeFile(filename, data, encoding='utf8', [callback])
fs.writeFileSync(filename, data, encoding='utf8')
fs.watchFile(filename, [options], listener)
fs.unwatchFile(filename)

fs.Stats[options], listener) fs.unwatchFile(filename) fs.ReadStream fs.createReadStream(path, [options])

fs.ReadStream fs.createReadStream(path, [options])[options], listener) fs.unwatchFile(filename) fs.Stats fs.WriteStream Event: 'open'

fs.WriteStream Event: 'open' fs.createWriteStream(path, [options])[options], listener) fs.unwatchFile(filename) fs.Stats fs.ReadStream fs.createReadStream(path, [options]) Path

Pathfs.createReadStream(path, [options]) fs.WriteStream Event: 'open' fs.createWriteStream(path, [options])

fs.createReadStream(path, [options]) fs.WriteStream Event: 'open' fs.createWriteStream(path, [options]) Path
path.join([path1], [path2], [ path.normalizeArray(arr) path.normalize(p) path.dirname(p) path.basename(p, [ext])

path.join([path1], [path2], [path.normalizeArray(arr) path.normalize(p) path.dirname(p) path.basename(p, [ext]) path.extname(p) path.exists(p,

path.normalizeArray(arr)path.join([path1], [path2], [ path.normalize(p) path.dirname(p) path.basename(p, [ext]) path.extname(p) path.exists(p,

path.normalize(p)path.join([path1], [path2], [ path.normalizeArray(arr) path.dirname(p) path.basename(p, [ext]) path.extname(p)

path.dirname(p)[path2], [ path.normalizeArray(arr) path.normalize(p) path.basename(p, [ext]) path.extname(p) path.exists(p,

path.basename(p, [ext])[ path.normalizeArray(arr) path.normalize(p) path.dirname(p) path.extname(p) path.exists(p, [callback]) ]) net

path.extname(p)path.normalize(p) path.dirname(p) path.basename(p, [ext]) path.exists(p, [callback]) ]) net

path.exists(p, [callback])path.dirname(p) path.basename(p, [ext]) path.extname(p) ]) net net.createServer(connectionListener)

])

net

net.createServer(connectionListener) net.createConnection(arguments

)

net.Servernet.createConnection(arguments ) server.listen(port, [host], [callback]) server.listen(path,

server.listen(port, [host], [callback])net.createConnection(arguments ) net.Server server.listen(path, [callback]) server.listenFD(fd)

server.listen(path, [callback])) net.Server server.listen(port, [host], [callback]) server.listenFD(fd) server.close() server.address()

server.listenFD(fd)[host], [callback]) server.listen(path, [callback]) server.close() server.address() server.maxConnections

server.close()server.listen(path, [callback]) server.listenFD(fd) server.address() server.maxConnections server.connections

server.address()[callback]) server.listenFD(fd) server.close() server.maxConnections server.connections Event:

server.maxConnectionsserver.listenFD(fd) server.close() server.address() server.connections Event: 'connection' Event:

server.connectionsserver.close() server.address() server.maxConnections Event: 'connection' Event: 'close'

Event: 'connection'server.address() server.maxConnections server.connections Event: 'close' net.Stream stream.connect(port,

Event: 'close'server.connections Event: 'connection' net.Stream stream.connect(port, [host], [callback])

net.StreamEvent: 'connection' Event: 'close' stream.connect(port, [host], [callback])

stream.connect(port, [host], [callback])'connection' Event: 'close' net.Stream stream.connect(path, [callback])

stream.connect(path, [callback]) stream.setEncoding(encoding=null) stream.setSecure([credentials])net.Stream stream.connect(port, [host], [callback]) stream.verifyPeer() stream.getPeerCertificate()

stream.verifyPeer() stream.getPeerCertificate()stream.setSecure([credentials]) stream.write(data, [encoding], [callback])

stream.write(data, [encoding], [callback])stream.verifyPeer() stream.getPeerCertificate() stream.write(data, [encoding], [fileDescriptor], [callback])

stream.write(data, [encoding], [fileDescriptor], [callback])stream.write(data, [encoding], [callback]) stream.end([data], [encoding]) stream.destroy()

stream.end([data], [encoding])stream.write(data, [encoding], [fileDescriptor], [callback]) stream.destroy() stream.pause() stream.resume()

stream.destroy()[fileDescriptor], [callback]) stream.end([data], [encoding]) stream.pause() stream.resume() stream.setTimeout(timeout)

stream.pause()[callback]) stream.end([data], [encoding]) stream.destroy() stream.resume() stream.setTimeout(timeout)

stream.resume() stream.setTimeout(timeout) stream.setNoDelay(noDelay=true) stream.setKeepAlive(enable=false, [initialDelay])[encoding]) stream.destroy() stream.pause() stream.remoteAddress Event: 'connect' Event:

stream.remoteAddressstream.setKeepAlive(enable=false, [initialDelay]) Event: 'connect' Event: 'data' Event:

Event: 'connect'[initialDelay]) stream.remoteAddress Event: 'data' Event: 'end' Event:

Event: 'data'stream.remoteAddress Event: 'connect' Event: 'end' Event: 'timeout' Event:

Event: 'end'Event: 'connect' Event: 'data' Event: 'timeout' Event: 'drain' Event:

Event: 'timeout''connect' Event: 'data' Event: 'end' Event: 'drain' Event: 'error' Event:

Event: 'drain''data' Event: 'end' Event: 'timeout' Event: 'error' Event: 'close' net.isIP

Event: 'error'Event: 'timeout' Event: 'drain' Event: 'close' net.isIP net.isIP(input)

Event: 'close'Event: 'drain' Event: 'error' net.isIP net.isIP(input) net.isIPv4(input) net.isIPv6(input)

net.isIPEvent: 'drain' Event: 'error' Event: 'close' net.isIP(input) net.isIPv4(input) net.isIPv6(input)

net.isIP(input)Event: 'drain' Event: 'error' Event: 'close' net.isIP net.isIPv4(input) net.isIPv6(input)

net.isIPv4(input)Event: 'drain' Event: 'error' Event: 'close' net.isIP net.isIP(input) net.isIPv6(input)

net.isIPv6(input)Event: 'drain' Event: 'error' Event: 'close' net.isIP net.isIP(input) net.isIPv4(input)

DNS dns.lookup(domain, family=null, callback)dns.resolve(domain, rrtype='A', callback) dns.resolve4(domain, callback) dns.resolve6(domain, callback)

DNS dns.lookup(domain, family=null, callback) dns.resolve(domain, rrtype='A', callback) dns.resolve4(domain,
dns.resolve(domain, rrtype='A', callback)

dns.resolve(domain, rrtype='A', callback)

dns.resolve4(domain, callback)

dns.resolve4(domain, callback)

dns.resolve6(domain, callback)

dns.resolve6(domain, callback)

dns.resolveMx(domain, callback)

dns.resolveMx(domain, callback)

dns.resolveTxt(domain, callback)

dns.resolveTxt(domain, callback)

dns.resolveSrv(domain, callback)

dns.resolveSrv(domain, callback)

dns.reverse(ip, callback)

dns.reverse(ip, callback)

dgram Event: 'message' Event: 'listening' Event: 'close' dgram.createSocket(type, [callback]) dgram.send(buf, offset, length, path, [callback]) dgram.send(buf, offset, length, port, address, [callback]) dgram.bind(path) dgram.bind(port, [address]) dgram.close() dgram.address() dgram.setBroadcast(flag) dgram.setTTL(ttl)callback) dns.reverse(ip, callback) HTTP http.Server Event: 'request' Event:

HTTPdgram.address() dgram.setBroadcast(flag) dgram.setTTL(ttl) http.Server Event: 'request' Event:

http.Server Event: 'request' Event: 'connection' Event: 'close' Event: 'request' Event: 'checkContinue' Event: 'upgrade' Event: 'clientError' http.createServer(requestListener) server.listen(port, [hostname], [callback]) server.listen(path, [callback]) server.close()dgram.setBroadcast(flag) dgram.setTTL(ttl) HTTP http.ServerRequest Event: 'data' Event:

http.ServerRequest Event: 'data' Event: 'end' request.method request.url request.headers request.trailers request.httpVersion request.setEncoding(encoding=null) request.pause() request.resume() request.connection[hostname], [callback]) server.listen(path, [callback]) server.close() http.ServerResponse response.writeContinue()

http.ServerResponse response.writeContinue()request.httpVersion request.setEncoding(encoding=null) request.pause() request.resume() request.connection

request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
request.pause() request.resume() request.connection http.ServerResponse response.writeContinue()
response.writeHead(statusCode, [reasonPhrase], [headers]) response.write(chunk, encoding='utf8')

response.writeHead(statusCode, [reasonPhrase], [headers]) response.write(chunk, encoding='utf8') response.addTrailers(headers)

response.end([data], [encoding])

response.end([data], [encoding])

http.Client Event: 'upgrade' Event: 'continue' http.createClient(port, host='localhost', secure=false, [credentials]) client.request(method='GET', path, [request_headers]) client.verifyPeer() client.getPeerCertificate()response.end([data], [encoding]) http.ClientRequest Event 'response'

http.ClientRequest Event 'response' request.write(chunk, encoding='utf8') request.end([data], [encoding])client.verifyPeer() client.getPeerCertificate() http.ClientResponse Event: 'data' Event:

http.ClientResponse Event: 'data' Event: 'end' response.statusCode response.httpVersion response.headers response.trailers response.setEncoding(encoding=null) response.pause() response.resume() response.clientencoding='utf8') request.end([data], [encoding]) URL url.parse(urlStr, parseQueryString=false)

URL url.parse(urlStr, parseQueryString=false) url.format(urlObj) url.resolve(from, to)response.pause() response.resume() response.client Query String querystring.stringify(obj, sep='&',

Query String querystring.stringify(obj, sep='&', eq='=') querystring.parse(str, sep='&', eq='=') querystring.escape querystring.unescapeurl.format(urlObj) url.resolve(from, to) REPL repl.start(prompt='> ',

REPL repl.start(prompt='> ', stream=process.stdin) REPL Featureseq='=') querystring.escape querystring.unescape Child Processes Event: 'exit' child.stdin

Child Processes Event: 'exit' child.stdin child.stdout child.stderr child.pid child_process.spawn(command, args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM')querystring.unescape REPL repl.start(prompt='> ', stream=process.stdin) REPL Features Assert

Assertargs=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM')

args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert
args=[], [options]) child_process.exec(command, [options], callback) child.kill(signal='SIGTERM') Assert

assert.fail(actual, expected, message, operator)assert.ok(value, [message]) assert.equal(actual, expected, [message]) assert.notEqual(actual, expected, [message])

assert.ok(value, [message])assert.fail(actual, expected, message, operator) assert.equal(actual, expected, [message]) assert.notEqual(actual,

assert.equal(actual, expected, [message])expected, message, operator) assert.ok(value, [message]) assert.notEqual(actual, expected, [message])

assert.notEqual(actual, expected, [message])[message]) assert.equal(actual, expected, [message]) assert.deepEqual(actual, expected, [message])

assert.deepEqual(actual, expected, [message]) assert.notDeepEqual(actual, expected, [message])[message]) assert.notEqual(actual, expected, [message]) assert.strictEqual(actual, expected, [message])

assert.strictEqual(actual, expected, [message]) assert.notStrictEqual(actual, expected, [message])[message]) assert.notDeepEqual(actual, expected, [message]) assert.throws(block, [error], [message])

assert.throws(block, [error], [message]) assert.doesNotThrow(block, [error], [message])assert.notStrictEqual(actual, expected, [message]) assert.ifError(value) TTY tty.open(path, args=[])

assert.ifError(value)[message]) assert.doesNotThrow(block, [error], [message]) TTY tty.open(path, args=[]) tty.isatty(fd)

TTY[error], [message]) assert.ifError(value) tty.open(path, args=[]) tty.isatty(fd) tty.setRawMode(mode)

tty.open(path, args=[])[error], [message]) assert.ifError(value) TTY tty.isatty(fd) tty.setRawMode(mode) tty.getColumns() os

tty.isatty(fd)[message]) assert.ifError(value) TTY tty.open(path, args=[]) tty.setRawMode(mode) tty.getColumns() os Module

tty.setRawMode(mode)TTY tty.open(path, args=[]) tty.isatty(fd) tty.getColumns() os Module os.hostname() os.type()

tty.getColumns()tty.open(path, args=[]) tty.isatty(fd) tty.setRawMode(mode) os Module os.hostname() os.type() os.release() os.uptime()

tty.isatty(fd) tty.setRawMode(mode) tty.getColumns() os Module os.hostname() os.type() os.release() os.uptime()

os Moduletty.isatty(fd) tty.setRawMode(mode) tty.getColumns() os.hostname() os.type() os.release() os.uptime()

os.hostname()tty.setRawMode(mode) tty.getColumns() os Module os.type() os.release() os.uptime() os.loadavg()

os.type()tty.getColumns() os Module os.hostname() os.release() os.uptime() os.loadavg() os.totalmem()

os.release()tty.getColumns() os Module os.hostname() os.type() os.uptime() os.loadavg() os.totalmem() os.freemem()

os.uptime()os Module os.hostname() os.type() os.release() os.loadavg() os.totalmem() os.freemem() os.cpus() Appendixes

os.loadavg()os Module os.hostname() os.type() os.release() os.uptime() os.totalmem() os.freemem() os.cpus() Appendixes Appendix 1 -

os.totalmem()os.type() os.release() os.uptime() os.loadavg() os.freemem() os.cpus() Appendixes Appendix 1 - Third Party

os.freemem()os.release() os.uptime() os.loadavg() os.totalmem() os.cpus() Appendixes Appendix 1 - Third Party Modules

os.cpus()os.uptime() os.loadavg() os.totalmem() os.freemem() Appendixes Appendix 1 - Third Party Modules Synopsis An

Appendixes

Appendix 1 - Third Party Modulesos.loadavg() os.totalmem() os.freemem() os.cpus() Appendixes Synopsis An example of a web server written with Node

Synopsis

An example of a web server written with Node which responds with 'Hello World':

var http = require('http');

http.createServer(function (request, response) { response.writeHead(200, {'Content-Type': 'text/plain'}); response.end('Hello World\n');

}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

To run the server, put the code into a file called the node program

example.js

and execute it with

> node example.js Server running at http://127.0.0.1:8124/

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

Global Objects

These object are available in the global scope and can be accessed from anywhere.

global

The global namespace object.

process

The process object. See the

'process object'

section.

require()

To require modules. See the

'Modules'

section.

require.resolve()

Use the internal

rather than loading the module, just return the resolved filename.

require()

machinery to look up the location of a module, but

require.paths

An array of search paths for paths.

require()

. This array can be modified to add custom

Example: add a new path to the beginning of the search list

require.paths.unshift('/usr/local/node');

filename

The filename of the script being executed. This is the absolute path, and not necessarily the same filename passed in as a command line argument.

Example: running

node example.js

from

/Users/mjr

not necessarily the same filename passed in as a command line argument. Example: running node example.js
not necessarily the same filename passed in as a command line argument. Example: running node example.js

console.log( filename); // /Users/mjr/example.js

dirname

The dirname of the script being executed.

Example: running

node example.js

from

/Users/mjr

console.log( dirname); // /Users/mjr

module

A reference to the current module. In particular

module.exports

the exports object. See Timers
the
exports
object. See
Timers

src/node.js

for more information.

is the same as

setTimeout(callback, delay, [arg], [

])

To schedule execution of

timeoutId

callback after delay

milliseconds. Returns a

for possible use with

clearTimeout()

. Optionally, you can also pass

arguments to the callback.

clearTimeout(timeoutId)

Prevents a timeout from triggering.

setInterval(callback, delay, [arg], [

])

To schedule the repeated execution of

Returns a

can also pass arguments to the callback.

callback every delay milliseconds.

intervalId

for possible use with

clearInterval()

. Optionally, you

clearInterval(intervalId)

Stops a interval from triggering.

Standard Modules

Node comes with a number of modules that are compiled in to the process, most of which are documented below. The most common way to use these modules is with

require('name')

and then assigning the return value to a local variable with the

same name as the module.

Example:

var util = require('util');

It is possible to extend node with other modules. See

'Modules'

Modules

Node uses the CommonJS module system.

Node has a simple module loading system. In Node, files and modules are in one-

to-one correspondence. As an example, the same directory.

foo.js
foo.js

loads the module

circle.js

in

The contents of

foo.js :
foo.js
:

var circle = require('./circle'); console.log( 'The area of a circle of radius 4 is ' + circle.area(4));

The contents of circle.js :

var PI = 3.14;

exports.area = function (r) { return PI * r * r;

};

exports.circumference = function (r) { return 2 * PI * r;

};

The module circle.js

has exported the functions

area() and exports object. exports .) Variables local to the PI is private to circle.js
area()
and
exports
object.
exports
.) Variables local to the
PI
is private to
circle.js
.

circumference()

puts()
puts()

. To export an object, add to the special

this
this

instead of

(Alternatively, one can use

module will be private. In this example the variable

The function

comes from the module

'util' , which is a built-in module.

Modules which are not prefixed by later.

'./'
'./'

are built-in module--more about this

Module Resolving

A module prefixed with

circle.js

find it.

'./'
'./'

is relative to the file calling

for

must be in the same directory as

foo.js
foo.js

require()

. That is,

require('./circle')

to

Without the leading

the

'./' require.paths array.

require('assert') require.paths
require('assert')

require('assert')

require('assert') require.paths
require.paths

require.paths

, like

the module is searched for in

on my system looks like this:

[ '/home/ryan/.node_modules' ]

That is, when

require('foo')

is called Node looks for:

1: /home/ryan/.node_modules/foo /home/ryan/.node_modules/foo

2: /home/ryan/.node_modules/foo.js /home/ryan/.node_modules/foo.js

3: /home/ryan/.node_modules/foo.node /home/ryan/.node_modules/foo.node

4: /home/ryan/.node_modules/foo/index.js /home/ryan/.node_modules/foo/index.js

5: /home/ryan/.node_modules/foo/index.node /home/ryan/.node_modules/foo/index.node

interrupting once a file is found. Files ending in

Modules; see 'Addons' below. directory.

'.node'
'.node'

are binary Addon

'index.js'

allows one to package a module as a

require.paths

can be modified at runtime by simply unshifting new paths onto it,

or at startup with the

paths, colon separated). Additionally node will search for directories called

NODE_PATH

environmental variable (which should be a list of

node_modules

starting at the current directory (of the module calling

require )
require
)

and upwards towards the root of the package tree. This feature makes it easy to have different module versions for different environments. Imagine the situation where you have a devopment environment and a production environment each with

a

different version of the

foo

module:

projects/x/development/node_modules/foo

projects/x/production/node_modules/foo

.

and

The second time

looks in the

require('foo') require.cache
require('foo')

require('foo')

require('foo') require.cache
require.cache

require.cache

is called, it is not loaded again from disk. It

object to see if it has been loaded before.

To get the exact filename that will be loaded when

require.resolve()

function.

require()

is called, use the

Addons

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

libraries:

V8 JavaScript, a C++ library. Used for interfacing with JavaScript: creatingobjects, calling functions, etc. Documented mostly in the ( deps/v8/include/v8.h in the Node source tree).

objects, calling functions, etc. Documented mostly in the

( deps/v8/include/v8.h

in the Node source tree).

v8.h
v8.h

header file

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 bein the Node source tree). v8.h header file used. Node uses the here . EV_DEFAULT event

used. Node uses the

here.

EV_DEFAULT

event loop. Documentation can be found

libeio, C thread pool library. Used to execute blocking POSIX system callsthe here . EV_DEFAULT event loop. Documentation can be found asynchronously. Mostly wrappers already exist for

asynchronously. Mostly wrappers already exist for such calls, in

so you will probably not need to use it. If you do need it, look at the header file

src/file.cc

deps/libeio/eio.h

.

Internal Node libraries. Most importantly is the which you will likely want to derive from.look at the header file src/file.cc deps/libeio/eio.h . Others. Look in node::ObjectWrap deps/ for what else

Others. Look inis the which you will likely want to derive from. node::ObjectWrap deps/ for what else is

node::ObjectWrap

deps/
deps/

for what else is available.

class

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

To get started let's make a small Addon which does the following except in C++:

exports.hello = 'world';

To get started we create a file

hello.cc

:

#include <v8.h>

using namespace v8;

extern "C" void

init (Handle<Object> target)

{

HandleScope scope; target->Set(String::New("hello"), String::New("world"));

}

This source code needs to be built into

we create a file called

hello.node

, the binary Addon. To do this

wscript
wscript

which is python code and looks like this:

srcdir = '.' blddir = 'build' VERSION = '0.0.1'

def set_options(opt):

opt.tool_options('compiler_cxx')

def configure(conf):

conf.check_tool('compiler_cxx')

conf.check_tool('node_addon')

def build(bld):

obj = bld.new_task_gen('cxx', 'shlib', 'node_addon') obj.target = 'hello' obj.source = 'hello.cc'

Running node-waf configure build will create a file

build/default/hello.node

which is our Addon.

node-waf

is just WAF, the python-based build system.

the ease of users.

node-waf

is provided for

All Node addons must export a function called

init
init

with this signature:

extern 'C' void init (Handle<Object> target)

For the moment, that is all the documentation on addons. Please see http://github.com/ry/node_postgres for a real example.

process

The process

object is a global object and can be accessed from anywhere. It is an

instance of EventEmitter .

Event: 'exit'

function () {}

Emitted when the process is about to exit. This is a good hook to perform constant time checks of the module's state (like for unit tests). The main event loop will no longer be run after the 'exit' callback finishes, so timers may not be scheduled.

Example of listening for

exit :
exit
:

process.on('exit', function () { process.nextTick(function () { console.log('This will not run'); }); console.log('About to exit.');

});

Event: 'uncaughtException'

function (err) { }

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

Example of listening for

uncaughtException

:

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. nonexistentFunc(); console.log('This will not run.');

Note that

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,

uncaughtException

is a very crude mechanism for exception handling.

uncaughtException

can be a useful safety mechanism.

Signal Events

function () {}

Emitted when the processes receives a signal. See sigaction(2) for a list of standard POSIX signal names such as SIGINT, SIGUSR1, etc.

Example of listening for

SIGINT :
SIGINT
:

// Start reading from stdin so we don't exit. process.stdin.resume();

process.on('SIGINT', function () { console.log('Got SIGINT. Press Control-D to exit.');

});

An easy way to send the programs.

signal is with}); An easy way to send the programs. process.stdout A Writable Stream to stdout . Example:

process.stdout

A

Writable Stream

to

stdout .
stdout
.

Example: the definition of

console.log

Control-C

in most terminal

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

};

process.stdin

A

call

Readable Stream

Readable Stream

Readable Stream process.stdin.resume()
process.stdin.resume()

process.stdin.resume()

Readable Stream process.stdin.resume()

for stdin. The stdin stream is paused by default, so one must

to read from it.

Example of opening standard input and listening for both events:

process.stdin.resume();

process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) { process.stdout.write('data: ' + chunk); });

process.stdin.on('end', function () { process.stdout.write('end'); });

process.argv

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

process.argv.forEach(function (val, index, array) { console.log(index + ': ' + val); });

This will generate:

$ 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

process.execPath

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

Example:

/usr/local/bin/node

process.chdir(directory)

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

console.log('Starting directory: ' + process.cwd()); try { process.chdir('/tmp'); console.log('New directory: ' + process.cwd());

}

catch (err) { console.log('chdir: ' + err);

}

process.cwd()

Returns the current working directory of the process.

console.log('Current directory: ' + process.cwd());

process.env

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

process.exit(code=0)

Ends the process with the specified

code
code

To exit with a 'failure' code:

. If omitted, exit uses the 'success' code

0 .
0
.

process.exit(1);

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

process.getgid()

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

console.log('Current gid: ' + process.getgid());

process.setgid(id)

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

console.log('Current gid: ' + process.getgid()); try {

process.setgid(501);

console.log('New gid: ' + process.getgid());

}

catch (err) { console.log('Failed to set gid: ' + err);

}

process.getuid()

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

console.log('Current uid: ' + process.getuid());

process.setuid(id)

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

console.log('Current uid: ' + process.getuid()); try {

process.setuid(501);

console.log('New uid: ' + process.getuid());

}

catch (err) { console.log('Failed to set uid: ' + err);

}

process.version

A compiled-in property that exposes

NODE_VERSION .

console.log('Version: ' + process.version);

process.installPrefix

A compiled-in property that exposes

NODE_PREFIX .

console.log('Prefix: ' + process.installPrefix);

process.kill(pid, signal='SIGINT')

Send a signal to a process.

describing the signal to send. Signal names are strings like 'SIGINT' or 'SIGUSR1'. If omitted, the signal will be 'SIGINT'. See kill(2) for more information.

pid
pid

is the process id and

signal
signal

is the string

Note that just because the name of this function is

signal sender, like the

than kill the target process.

process.kill

, it is really just a

kill
kill

system call. The signal sent may do something other

Example of sending a signal to yourself:

process.on('SIGHUP', function () { console.log('Got SIGHUP signal.'); });

setTimeout(function () { console.log('Exiting.');

process.exit(0);

}, 100);

process.kill(process.pid, 'SIGHUP');

process.pid

The PID of the process.

console.log('This process is pid ' + process.pid);

process.title

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

process.platform

What platform you're running on.

'linux2'

,

'darwin'

, etc.

console.log('This platform is ' + process.platform);

process.memoryUsage()

Returns an object describing the memory usage of the Node process.

var util = require('util');

console.log(util.inspect(process.memoryUsage()));

This will generate:

{ rss: 4935680, vsize: 41893888, heapTotal: 1826816, heapUsed: 650472 }

heapTotal

and

heapUsed

refer to V8's memory usage.

process.nextTick(callback)

On the next loop around the event loop call this callback. This is not a simple alias

to

setTimeout(fn, 0)

, it's much more efficient.

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

process.umask([mask])

Sets or reads the process's file mode creation mask. Child processes inherit the mask

from the parent process. Returns the old mask if returns the current mask.

argument is given, otherwise

mask
mask

var oldmask, newmask = 0644;

oldmask = process.umask(newmask); console.log('Changed umask from: ' + oldmask.toString(8) + ' to ' + newmask.toString(8));

util

These functions are in the module

'util'
'util'

. Use

require('util')

to access them.

util.debug(string)

A synchronous output function. Will block the process and output

immediately to

stderr .
stderr
.
string
string

require('util').debug('message on stderr');

util.log(string)

Output with timestamp on

stdout .
stdout
.

require('util').log('Timestmaped message.');

util.inspect(object, showHidden=false,

depth=2)

Return a string representation of

object
object

, which is useful for debugging.

If showHidden is true , then the object's non-enumerable properties will be shown too. If
If
showHidden
is
true
, then the object's non-enumerable properties will be shown
too.
If
depth
is provided, it tells
inspect
how many times to recurse while formatting
the object. This is useful for inspecting large complicated objects.
The default is to only recurse twice. To make it recurse indefinitely, pass in
null
for
depth
.

Example of inspecting all properties of the

util
util

object:

var util = require('util');

console.log(util.inspect(util, true, null));

util.pump(readableStream, writeableStream, [callback])

Experimental

Read the data from

readableStream

and send it to the

writableStream

. When

writeableStream.write(data) returns

until the drain event occurs on the

 

false

readableStream

writableStream

.

callback

 

writableStream

   

will be paused

gets an error as

its only argument and is called when occurs.

is closed or when an error

util.inherits(constructor, superConstructor)

Inherit the prototype methods from one constructor into another. The prototype of

constructor

will be set to a new object created from

superConstructor

.

As an additional convenience,

superConstructor

constructor.super_

property.

will be accessible through the

var util = require("util"); var events = require("events");

function MyStream() { events.EventEmitter.call(this);

}

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!"

Events

Many objects in Node emit events: a

connects to it, a

net.Server

emits an event each time a peer

fs.readStream

emits an event when the file is opened. All objects

which emit events are instances of

module by doing:

events.EventEmitter require("events");
events.EventEmitter

events.EventEmitter

events.EventEmitter require("events");
require("events");

require("events");

. You can access this

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

Functions can be then be attached to objects, to be executed when an event is emitted. These functions are called listeners.

events.EventEmitter

To access the EventEmitter class,

require('events').EventEmitter

.

When an

an

listener for it, then the default action is to print a stack trace and exit the program.

EventEmitter 'error'
EventEmitter

EventEmitter

EventEmitter 'error'
'error'

'error'

instance experiences an error, the typical action is to emit

event. Error events are treated as a special case in node. If there is no

All EventEmitters emit the event

'newListener'

when new listeners are added.

emitter.addListener(event, listener) emitter.on(event, listener)

Adds a listener to the end of the listeners array for the specified event.

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

emitter.once(event, listener)

Adds a one time listener for the event. The listener is invoked only the first time the event is fired, after which it is removed.

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

emitter.removeListener(event, listener)

Remove a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.

var callback = function(stream) { console.log('someone connected!');

}; server.on('connection', callback); //

server.removeListener('connection', callback);

emitter.removeAllListeners(event)

Removes all listeners from the listener array for the specified event.

emitter.listeners(event)

Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners.

This array can be manipulated, e.g. to remove listeners. server . on ( 'connection' , function

server.on('connection', function (stream) { console.log('someone connected!'); }); console.log(util.inspect(server.listeners('connection')); // [ [Function] ]

emitter.emit(event, [arg1], [arg2], [

])

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

Event: 'newListener'

function (event, listener) { }

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

Buffers

Pure Javascript is Unicode friendly but not nice to binary data. When dealing with TCP streams or the file system, it's necessary to handle octet streams. Node has several strategies for manipulating, creating, and consuming octet streams.

Raw data is stored in instances of the

of integers but corresponds to a raw memory allocation outside the V8 heap. A

Buffer
Buffer

class. A

Buffer
Buffer

is similar to an array

Buffer
Buffer

cannot be resized.

The

Buffer
Buffer

object is global.

Converting between Buffers and JavaScript string objects requires an explicit encoding method. Here are the different string encodings;

'ascii'
'ascii'

- for 7 bit ASCII data only. This encoding method is very fast, and

will strip the high bit if set.

'utf8'- Unicode characters. Many web pages and other document formats use UTF-8. 'base64' 'binary' -

- Unicode characters. Many web pages and other document formats

use UTF-8. 'base64' 'binary'
use UTF-8.
'base64'
'binary'

- Base64 string encoding.

- A way of encoding raw binary data into strings by using only the

first 8 bits of each character. This encoding method is depreciated and should

be avoided in favor of

removed in future versions of Node.

Buffer
Buffer

objects where possible. This encoding will be

new Buffer(size)

Allocates a new buffer of

size
size

octets.

new Buffer(array)

Allocates a new buffer using an

array
array

of octets.

new Buffer(str, encoding='utf8')

Allocates a new buffer containing the given

str .
str
.

buffer.write(string, offset=0, encoding='utf8')

Writes

of octets written. If

will write a partial amount of the string. In the case of method will not write partial characters.

string
string

to the buffer at

buffer
buffer
offset
offset

using the given encoding. Returns number

did not contain enough space to fit the entire string it

'utf8'
'utf8'

encoding, the

Example: write a utf8 string into a buffer, then print it

buf = new Buffer(256); len = buf.write('\u00bd + \u00bc = \u00be', 0); console.log(len + " bytes: " + buf.toString('utf8', 0, len));

// 12 bytes: ½ + ¼ = ¾

buffer.toString(encoding, start=0, end=buffer.length)

Decodes and returns a string from buffer data encoded with

at

encoding

start
start

and ending at

end .
end
.

See

buffer.write()

example, above.

buffer[index]

beginning

Get and set the octet at

range is between

index 0x00 and 0xFF
index
0x00
and
0xFF

. The values refer to individual bytes, so the legal

hex or

0
0

and

255 .
255
.

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

str = "node.js"; buf = new Buffer(str.length);

for (var i = 0; i < str.length ; i++) { buf[i] = str.charCodeAt(i);

}

console.log(buf);

// node.js

Buffer.isBuffer(obj)

Tests if

obj
obj

is a

Buffer .
Buffer
.

Buffer.byteLength(string, encoding='utf8')

Gives the actual byte length of a string. This is not the same as

String.prototype.length

string.

Example:

since that returns the number of characters in a

str = '\u00bd + \u00bc = \u00be';

console.log(str + ": " + str.length + " characters, " + Buffer.byteLength(str, 'utf8') + " bytes");

// ½ + ¼ = ¾: 9 characters, 12 bytes

buffer.length

The size of the buffer in bytes. Note that this is not necessarily the size of the

contents.

does not change when the contents of the buffer are changed.

length
length

refers to the amount of memory allocated for the buffer object. It

when the contents of the buffer are changed. length refers to the amount of memory allocated
when the contents of the buffer are changed. length refers to the amount of memory allocated

buf = new Buffer(1234);

console.log(buf.length); buf.write("some string", "ascii", 0); console.log(buf.length);

// 1234

// 1234

buffer.copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)

Does a memcpy() between buffers.

Example: build two Buffers, then copy

buf2
buf2

, starting at the 8th byte in

buf1 buf2 .
buf1
buf2
.

from byte 16 through byte 19 into

buf1 = new Buffer(26); buf2 = new Buffer(26);

for (var i = 0 ; i < 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!!!!!!!!!!!!!

buffer.slice(start, end=buffer.length)

Returns a new buffer which references the same memory as the old, but offset and

cropped by the

start
start

and

end
end

indexes.

Modifying the new buffer slice will modify memory in the original buffer!

Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte from the original Buffer.

buffer! Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte
buffer! Example: build a Buffer with the ASCII alphabet, take a slice, then modify one byte

var buf1 = new Buffer(26);

for (var i = 0 ; i < 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

Streams

A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout. Streams are readable,

writable, or both. All streams are instances of

Readable Stream

EventEmitter

.

A

Readable Stream

has the following methods, members, and events.

Event: 'data'

function (data) { }

The 'data' was used.
The
'data'
was used.

event emits either a

Buffer
Buffer

(by default) or a string if

setEncoding()

Event: 'end'

function () { }

Emitted when the stream has received an EOF (FIN in TCP terminology). Indicates

that no more

possible to continue writing.

'data'
'data'

events will happen. If the stream is also writable, it may be

Event: 'error'

function (exception) { }

Emitted if there was an error receiving data.

Event: 'close'

function () { }

Emitted when the underlying file descriptor has be closed. Not all streams will emit

this. (For example, an incoming HTTP request will not emit

'close'
'close'

.)

Event: 'fd'

function (fd) { }

Emitted when a file descriptor is received on the stream. Only UNIX streams support this functionality; all others will simply never emit this event.

stream.readable

A boolean that is

stream came to an

true 'end'
true
'end'

by default, but turns

, or

false destroy()
false
destroy()

was called.

after an

'error'
'error'

occured, the

stream.setEncoding(encoding)

Makes the data event emit a string instead of a

'ascii'
'ascii'

, or

'base64'

.

Buffer . encoding
Buffer
. encoding

stream.pause()

Pauses the incoming

'data'
'data'

events.

stream.resume()

Resumes the incoming

'data'
'data'

events after a

pause() .
pause()
.

can be

'utf8' ,
'utf8'
,

stream.destroy()

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

stream.pipe(destination, [options])

This is a

Stream.prototype

method available on all

Stream
Stream

s.

Connects this read stream to

stream gets written to

in sync by pausing and resuming as necessary.

destination destination
destination

destination

destination destination
destination

destination

WriteStream. Incoming data on this

. The destination and source streams are kept

Emulating the Unix

cat
cat

command:

process.stdin.pipe(process.stdout);

By default

that

keep the destination stream open.

end() destination
end()
destination

is called on the destination when the source stream emits

is no longer writable. Pass

{ end: false }

as

end options to
end
options
to

This keeps

process.stdout

open so that "Goodbye" can be written at the end.

, so

process.stdin.resume();

process.stdin.pipe(process.stdout, { end: false });

process.stdin.on("end", function() { process.stdout.write("Goodbye\n"); });

NOTE: If the source stream does not support

function adds simple definitions which simply emit on the source stream.

Writable Stream

pause()

and

resume()

, this

 

'pause'

and

'resume'

A

Writable Stream

has the following methods, members, and events.

events

Event: 'drain'

function () { }

Emitted after a

is safe to write again.

write()
write()

method was called that returned

false
false

to indicate that it

Event: 'error'

function (exception) { }

Emitted on error with the exception

Event: 'close'

function () { }

exception

.

Emitted when the underlying file descriptor has been closed.

stream.writeable

A boolean that is true by default, but turns false end() / destroy() was called.
A
boolean that is
true
by default, but turns
false
end()
/
destroy()
was called.

after an

occurred orbut turns false end() / destroy() was called. after an stream.write(string, encoding='utf8', [fd]) Writes

stream.write(string, encoding='utf8', [fd])

Writes

has been flushed to the kernel buffer. Returns

with the given

string
string

encoding

to the stream. Returns

false
false

if the stringwith the given string encoding to the stream. Returns false to indicate that the kernel buffer

to indicate that the kernel

buffer is full, and the data will be sent out in the future. The 'drain'
buffer is full, and the data will be sent out in the future. The
'drain'
event will
indicate when the kernel buffer is empty again. The
encoding
defaults to
'utf8'
.
If the optional
fd
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.

stream.write(buffer)

Same as the above except with a raw buffer.

stream.end()

Terminates the stream with EOF or FIN.

stream.end(string, encoding)

Sends

FIN. This is useful to reduce the number of packets sent.

string
string

with the given

encoding

and terminates the stream with EOF or

stream.end(buffer)

Same as above but with a

buffer .
buffer
.

stream.destroy()

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

Crypto

Use

require('crypto')

to access this module.

The crypto module requires OpenSSL to be available on the underlying platform. It offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or http connection.

It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign

and verify methods.

crypto.createCredentials(details)

Creates a credentials object, with the optional details being a dictionary with keys:

key : a string holding the PEM encoded private key : a string holding the PEM encoded private key

cert : a string holding the PEM encoded certificate : a string holding the PEM encoded certificate

ca : either a string or list of strings of PEM encoded CA certificates to trust. : either a string or list of strings of PEM encoded CA certificates to trust.

If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt.

crypto.createHash(algorithm)

Creates and returns a hash object, a cryptographic hash with the given algorithm which can be used to generate hash digests.

algorithm

is dependent on the available algorithms supported by the version of

OpenSSL on the platform. Examples are

etc. On recent releases,

the available digest algorithms.

 

'sha1'

,

'md5'

,

'sha256'

,

'sha512'

,

openssl list-message-digest-algorithms

 

will display

hash.update(data)

Updates the hash content with the given new data as it is streamed.

This can be called many times withthe hash content with the given new data as it is streamed. hash.digest(encoding='binary') Calculates the digest

hash.digest(encoding='binary')

Calculates the digest of all of the passed data to be hashed. The

'hex' , 'binary'
'hex'
, 'binary'

or 'base64' .

encoding

can be

crypto.createHmac(algorithm, key)

Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.

algorithm

is dependent on the available algorithms supported by OpenSSL - see

createHash above.

key
key

is the hmac key to be used.

hmac.update(data)

Update the hmac content with the given new data as it is streamed.

This can be called many times withthe hmac content with the given new data as it is streamed. hmac.digest(encoding='binary') Calculates the digest

hmac.digest(encoding='binary')

Calculates the digest of all of the passed data to the hmac. The

'hex' , 'binary'
'hex'
, 'binary'

or 'base64' .

encoding

can be

crypto.createCipher(algorithm, key)

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

algorithm

is dependent on OpenSSL, examples are

'aes192'

, etc. On recent

releases, openssl list-cipher-algorithms

will display the available cipher

algorithms.

cipher.update(data, input_encoding='binary', output_encoding='binary')

Updates the cipher with

and can be

output format of the enciphered data, and can be

data 'utf8' , 'ascii'
data
'utf8'
, 'ascii'

, the encoding of which is given in

or

'binary'

. The

input_encoding

output_encoding

specifies the

or

'hex' .
'hex'
.

'binary'

,

'base64'

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

cipher.final(output_encoding='binary')

Returns any remaining enciphered contents, with

'binary' , 'ascii'
'binary'
, 'ascii'

or

'utf8' .
'utf8'
.

output_encoding

being one of:

crypto.createDecipher(algorithm, key)

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

decipher.update(data,

input_encoding='binary',

output_encoding='binary')

Updates the decipher with

'hex'
'hex'