0% found this document useful (0 votes)
565 views

NodeJS Cheat Sheet - OverAPI

The document provides a summary of Node.js core modules and APIs in 3 sentences or less per section. It covers global objects, modules, buffers, streams, processes, domains, console, addons, crypto, timers, events, utilities, files, paths, query strings, punycode, networking and streams. Key classes and methods are listed for each along with links to the official documentation.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
565 views

NodeJS Cheat Sheet - OverAPI

The document provides a summary of Node.js core modules and APIs in 3 sentences or less per section. It covers global objects, modules, buffers, streams, processes, domains, console, addons, crypto, timers, events, utilities, files, paths, query strings, punycode, networking and streams. Key classes and methods are listed for each along with links to the official documentation.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

1/30/13

Search

NodeJS Cheat Sheet | OverAPI.com

Resource
Online
Official Website

Basic
Global Objects
global process console Class: Buffer require() require.resolve() require.cache require.extensions __filename __dirname module exports setTimeout(cb, ms) clearTimeout(t) setInterval(cb, ms) clearInterval(t)

Module
Modules
Cycles Core Modules File Modules Loading from n o d e _ m o d u l e sF olders Folders as Modules Caching Module Caching Caveats The m o d u l eObject module.exports module.require(id) module.id module.filename module.loaded module.parent module.children All Together... Loading from the global folders Accessing the main module Addenda: Package Manager Ti ps

Buffer/Stream
Buffer
Buffer Class: Buffer new Buffer(size) new Buffer(array) new Buffer(str, [encoding]) buf.write(string, [offset], [length] , [encoding]) buf.toString([encoding], [start], [ end]) buf[index] Class Method: Buffer.isBuffer(o bj) Class Method: Buffer.byteLengt h(string, [encoding]) Class Method: Buffer.concat(list , [totalLength]) buf.length buf.copy(targetBuffer, [targetSt art], [sourceStart], [sourceEnd]) buf.slice([start], [end]) buf.readUInt8(offset, [noAssert] ) buf.readUInt16LE(offset, [noAs sert]) buf.readUInt16BE(offset, [noAs sert]) buf.readUInt32LE(offset, [noAs sert]) buf.readUInt32BE(offset, [noAs sert]) buf.readInt8(offset, [noAssert]) buf.readInt16LE(offset, [noAsse rt]) buf.readInt16BE(offset, [noAss ert]) buf.readInt32LE(offset, [noAsse rt]) buf.readInt32BE(offset, [noAss ert]) buf.readFloatLE(offset, [noAss ert]) buf.readFloatBE(offset, [noAss ert]) buf.readDoubleLE(offset, [noAs sert]) buf.readDoubleBE(offset, [noAs sert]) buf.writeUInt8(value, offset, [no Assert]) buf.writeUInt16LE(value, offset, [noAssert]) buf.writeUInt16BE(value, offset, [noAssert]) buf.writeUInt32LE(value, offset, [noAssert]) buf.writeUInt32BE(value, offset, [noAssert]) buf.writeInt8(value, offset, [noA ssert]) buf.writeInt16LE(value, offset, [ noAssert]) buf.writeInt16BE(value, offset, [ noAssert]) buf.writeInt32LE(value, offset, [ noAssert]) buf.writeInt32BE(value, offset, [ noAssert]) buf.writeFloatLE(value, offset, [ noAssert]) buf.writeFloatBE(value, offset, [ noAssert]) buf.writeDoubleLE(value, offset , [noAssert]) buf.writeDoubleBE(value, offset , [noAssert]) buf.fill(value, [offset], [end]) buffer.INSPECT_MAX_BYTES Class: SlowBuffer

Process/Eve
Process

Related
JavaScript

Domain
Domain
Additions to Error objects Implicit Binding Explicit Binding domain.create() Class: Domain domain.run(fn) domain.members domain.add(emitter) domain.remove(emitter) domain.bind(cb) Example domain.intercept(cb) Example domain.dispose()

console
console.log([data], [...]) console.info([data], [...]) console.error([data], [...]) console.warn([data], [...]) console.dir(obj) console.time(label) console.timeEnd(label) console.trace(label) console.assert(expression, [me ssage])

Addons
Addons Hello world Addon patterns Function arguments Callbacks Object factory Function factory Wrapping C++ objects Factory of wrapped objects Passing wrapped objects aroun d

Crypto
crypto.createCredentials(detail s) crypto.createHash(algorithm) Class: Hash hash.update(data, [input_enco ding]) hash.digest([encoding]) crypto.createHmac(algorithm, k ey) Class: Hmac hmac.update(data) hmac.digest([encoding]) crypto.createCipher(algorithm, password) crypto.createCipheriv(algorithm , key, iv) Class: Cipher cipher.update(data, [input_enc oding], [output_encoding]) cipher.final([output_encoding]) cipher.setAutoPadding(auto_pa dding=true) crypto.createDecipher(algorith m, password) crypto.createDecipheriv(algorit hm, key, iv) Class: Decipher decipher.update(data, [input_e ncoding], [output_encoding]) decipher.final([output_encoding ]) decipher.setAutoPadding(auto_ padding=true) crypto.createSign(algorithm) Class: Signer signer.update(data) signer.sign(private_key, [output _format]) crypto.createVerify(algorithm) Class: Verify verifier.update(data) verifier.verify(object, signature, [signature_format]) crypto.createDiffieHellman(prim e_length) crypto.createDiffieHellman(prim e, [encoding]) Class: DiffieHellman diffieHellman.generateKeys([en coding]) diffieHellman.computeSecret(ot her_public_key, [input_encodin g], [output_encoding]) diffieHellman.getPrime([encodin g])

Timers
setTimeout(callback, delay, [ar g], [...]) clearTimeout(timeoutId) setInterval(callback, delay, [arg] , [...]) clearInterval(intervalId)

Event: 'exit' Event: 'uncaughtExceptio Signal Events process.stdout process.stderr process.stdin process.argv process.execPath process.abort() process.chdir(directory) process.cwd() process.env process.exit([code]) process.getgid() process.setgid(id) process.getuid() process.setuid(id) process.version process.versions process.config process.kill(pid, [signal]) process.pid process.title process.arch process.platform process.memoryUsage() process.nextTick(callback process.umask([mask]) process.uptime() process.hrtime()

Events

Util
util.format(format, [...]) util.debug(string) util.error([...]) util.puts([...]) util.print([...]) util.log(string) util.inspect(object, [showHidden ], [depth], [colors]) util.isArray(object) util.isRegExp(object) util.isDate(object) util.isError(object) util.pump(readableStream, writa bleStream, [callback]) util.inherits(constructor, superC onstructor)

File
File System
fs.rename(oldPath, newPath, [c allback]) fs.renameSync(oldPath, newPa th) fs.truncate(fd, len, [callback]) fs.truncateSync(fd, len) fs.chown(path, uid, gid, [callbac k]) fs.chownSync(path, uid, gid) fs.fchown(fd, uid, gid, [callback] ) fs.fchownSync(fd, uid, gid) fs.lchown(path, uid, gid, [callba ck]) fs.lchownSync(path, uid, gid) fs.chmod(path, mode, [callback] ) fs.chmodSync(path, mode) fs.fchmod(fd, mode, [callback]) fs.fchmodSync(fd, mode) fs.lchmod(path, mode, [callback ]) fs.lchmodSync(path, mode) fs.stat(path, [callback]) fs.lstat(path, [callback]) fs.fstat(fd, [callback]) fs.statSync(path) fs.lstatSync(path) fs.fstatSync(fd) fs.link(srcpath, dstpath, [callbac k]) fs.linkSync(srcpath, dstpath) fs.symlink(destination, path, [ty pe], [callback]) fs.symlinkSync(destination, pat h, [type]) fs.readlink(path, [callback]) fs.readlinkSync(path) fs.realpath(path, [cache], callba ck) fs.realpathSync(path, [cache]) fs.unlink(path, [callback])

Class: events.EventEmitte emitter.addListener(even ner) emitter.on(event, listener emitter.once(event, listen emitter.removeListener(e stener) emitter.removeAllListener nt]) emitter.setMaxListeners(n emitter.listeners(event) emitter.emit(event, [arg1] ], [...]) Event: 'newListener'

net

Text
Path
path.normalize(p) path.join([path1], [path2], [...]) path.resolve([from ...], to) path.relative(from, to) path.dirname(p) path.basename(p, [ext]) path.extname(p) path.sep

Query String
querystring.stringify(obj, [sep], [ eq]) querystring.parse(str, [sep], [eq ], [options]) querystring.escape querystring.unescape

punnycode
punycode.decode(string) punycode.encode(string) punycode.toUnicode(domain)

Stream
Readable Stream Event: 'data' Event: 'end'

net.createServer([options nectionListener]) net.connect(options, [con nListener]) net.createConnection(op connectionListener]) net.connect(port, [host], [ ctListener]) net.createConnection(po st], [connectListener]) net.connect(path, [conne ner]) net.createConnection(pa nnectListener]) Class: net.Server server.listen(port, [host], og], [listeningListener]) server.listen(path, [listeni ener]) server.listen(handle, [liste stener]) server.close([cb]) server.address() server.maxConnections server.connections Event: 'listening' Event: 'connection' Event: 'close' Event: 'error' Class: net.Socket

overapi.com/nodejs/

1/3

1/30/13
diffieHellman.getGenerator([en coding]) diffieHellman.getPublicKey([enc oding]) diffieHellman.getPrivateKey([en coding]) diffieHellman.setPublicKey(publi c_key, [encoding]) diffieHellman.setPrivateKey(pub lic_key, [encoding]) crypto.getDiffieHellman(group_ name) crypto.pbkdf2(password, salt, it erations, keylen, callback) crypto.randomBytes(size, [callb ack])

NodeJS Cheat Sheet | OverAPI.com


punycode.toASCII(domain) punycode.ucs2 punycode.ucs2.decode(string) punycode.ucs2.encode(codePo ints) punycode.version 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], [cal lback]) fs.openSync(path, flags, [mode] ) fs.utimes(path, atime, mtime, [c allback]) fs.utimesSync(path, atime, mtim e) fs.futimes(fd, atime, mtime, [call back]) fs.futimesSync(fd, atime, mtime) fs.fsync(fd, [callback]) fs.fsyncSync(fd) fs.write(fd, buffer, offset, length, position, [callback]) fs.writeSync(fd, buffer, offset, le ngth, position) fs.read(fd, buffer, offset, length, position, [callback]) fs.readSync(fd, buffer, offset, le ngth, position) fs.readFile(filename, [encoding] , [callback]) fs.readFileSync(filename, [enco ding]) fs.writeFile(filename, data, [enc oding], [callback]) fs.writeFileSync(filename, data, [encoding]) fs.appendFile(filename, data, e ncoding='utf8', [callback]) fs.appendFileSync(filename, da ta, encoding='utf8') fs.watchFile(filename, [options], listener) fs.unwatchFile(filename) fs.watch(filename, [options], [list ener]) Caveats Availability Filename Argument fs.exists(path, [callback]) fs.existsSync(path) Class: fs.Stats fs.createReadStream(path, [opt ions]) Class: fs.ReadStream Event: 'open' fs.createWriteStream(path, [opt ions]) fs.WriteStream Event: 'open' file.bytesWritten Class: fs.FSWatcher watcher.close() Event: 'change' Event: 'error' Event: 'error' Event: 'close' stream.readable stream.setEncoding([encoding] ) stream.pause() stream.resume() stream.destroy() stream.pipe(destination, [option s]) Writable Stream Event: 'drain' Event: 'error' Event: 'close' Event: 'pipe' stream.writable stream.write(string, [encoding], [fd]) stream.write(buffer) stream.end() stream.end(string, encoding) stream.end(buffer) stream.destroy() stream.destroySoon()

Readline
readline.createInterface(option s) Class: Interface rl.setPrompt(prompt, length) rl.prompt([preserveCursor]) rl.question(query, callback) rl.pause() rl.resume() rl.close() rl.write(data, [key]) Events Event: 'line' Event: 'pause' Event: 'resume' Event: 'close' Event: 'SIGINT' Event: 'SIGTSTP' Event: 'SIGCONT' Example: Tiny CLI

TSL(SSL)
Client-initiated renegotiation att ack mitigation NPN and SNI tls.createServer(options, [secur eConnectionListener]) tls.connect(options, [secureCon nectListener]) tls.connect(port, [host], [options ], [secureConnectListener]) tls.createSecurePair([credential s], [isServer], [requestCert], [rej ectUnauthorized]) Class: SecurePair Event: 'secure' Class: tls.Server Event: 'secureConnection' Event: 'clientError' server.listen(port, [host], [callba ck]) server.close() server.address() server.addContext(hostname, c redentials) server.maxConnections server.connections Class: tls.CleartextStream Event: 'secureConnect' cleartextStream.authorized cleartextStream.authorizationEr ror cleartextStream.getPeerCertific ate() cleartextStream.getCipher() cleartextStream.address() cleartextStream.remoteAddress cleartextStream.remotePort

TTY
tty.isatty(fd) tty.setRawMode(mode) Class: ReadStream rs.isRaw rs.setRawMode(mode) Class WriteStream ws.columns ws.rows Event: 'resize'

REPL
repl.start(options) Event: 'exit' REPL Features

new net.Socket([options]) socket.connect(port, [hos nnectListener]) socket.connect(path, [con istener]) socket.bufferSize socket.setEncoding([enco socket.write(data, [encod allback]) socket.end([data], [encod socket.destroy() socket.pause() socket.resume() socket.setTimeout(timeou back]) socket.setNoDelay([noDe socket.setKeepAlive([ena nitialDelay]) socket.address() socket.remoteAddress socket.remotePort socket.bytesRead socket.bytesWritten Event: 'connect' Event: 'data' Event: 'end' Event: 'timeout' Event: 'drain' Event: 'error' Event: 'close' net.isIP(input) net.isIPv4(input) net.isIPv6(input)

UDP / Datagram Sock

HTTP
http
http.STATUS_CODES http.createServer([requestListe ner]) http.createClient([port], [host]) http.request(options, callback) http.get(options, callback) http.globalAgent

Code
Executing JS
Caveats Sandboxes Globals vm.runInThisContext(code, [file name]) vm.runInNewContext(code, [san dbox], [filename]) vm.runInContext(code, context, [filename]) vm.createContext([initSandbox] ) vm.createScript(code, [filename ]) Class: Script script.runInThisContext() script.runInNewContext([sandbo x])

Class: http.Server
Event: 'request' Event: 'connection' Event: 'close' Event: 'checkContinue' Event: 'connect' Event: 'upgrade' Event: 'clientError' server.listen(port, [hostname], [ backlog], [callback]) server.listen(path, [callback]) server.listen(handle, [listeningLi stener]) server.close([cb]) server.maxHeadersCount

StringDecoder
Class: StringDecoder StringDecoder.write(buffer)

dgram.createSocket(type ack]) Class: Socket Event: 'message' Event: 'listening' Event: 'close' Event: 'error' dgram.send(buf, offset, le port, address, [callback]) dgram.bind(port, [addres dgram.close() dgram.address() dgram.setBroadcast(flag) dgram.setTTL(ttl) dgram.setMulticastTTL(tt dgram.setMulticastLoopb g) dgram.addMembership(m stAddress, [multicastInter dgram.dropMembership(m stAddress, [multicastInter

DNS

System
Zlib
Examples zlib.createGzip([options]) zlib.createGunzip([options]) zlib.createDeflate([options]) zlib.createInflate([options]) zlib.createDeflateRaw([options]) zlib.createInflateRaw([options]) zlib.createUnzip([options]) Class: zlib.Gzip Class: zlib.Gunzip Class: zlib.Deflate Class: zlib.Inflate Class: zlib.DeflateRaw Class: zlib.InflateRaw Class: zlib.Unzip Convenience Methods zlib.deflate(buf, callback) zlib.deflateRaw(buf, callback) zlib.gzip(buf, callback) zlib.gunzip(buf, callback) zlib.inflate(buf, callback) zlib.inflateRaw(buf, callback) zlib.unzip(buf, callback) Options Memory Usage Tuning Constants

Child Process
Class: ChildProcess Event: 'exit' Event: 'close' Event: 'disconnect' Event: 'message' child.stdin child.stdout child.stderr child.pid child.kill([signal]) child.send(message, [sendHan dle]) child.disconnect() child_process.spawn(command , [args], [options]) child_process.exec(command, [ options], callback) child_process.execFile(file, arg s, options, callback) child_process.fork(modulePath, [args], [options])

Class: http.ServerReques t
Event: 'data' Event: 'end' Event: 'close' request.method request.url request.headers request.trailers request.httpVersion request.setEncoding([encoding ]) request.pause() request.resume() request.connection

3rd Party
Third Party Modules Module Installer:
npm

dns.lookup(domain, [fami lback) dns.resolve(domain, [rrty llback) dns.resolve4(domain, cal dns.resolve6(domain, cal dns.resolveMx(domain, ca ) dns.resolveTxt(domain, c k) dns.resolveSrv(domain, c k) dns.resolveNs(domain, ca ) dns.resolveCname(doma back) dns.reverse(ip, callback) Error codes

HTTP Middleware:
Connect

Web Framework:
Express

Class: http.ServerRespon se
Event: 'close' response.writeContinue() response.writeHead(statusCod e, [reasonPhrase], [headers]) response.statusCode response.setHeader(name, val ue) response.sendDate response.getHeader(name)

Web Sockets:
Socket.IO

Support U

HTML Parsing:
HTML5 mDNS/Zeroconf/Bonjour

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

/li>
RabbitMQ, AMQP mysql

Serialization:
msgpack

overapi.com/nodejs/

2/3

1/30/13

NodeJS Cheat Sheet | OverAPI.com


response.removeHeader(name ) response.write(chunk, [encodin g]) response.addTrailers(headers) response.end([data], [encoding ])

os
os.tmpDir() os.hostname() os.type() os.platform() os.arch() os.release() os.uptime() os.loadavg() os.totalmem() os.freemem() os.cpus() os.networkInterfaces() os.EOL

Scraping:
Apricot

Debugger:
ndb

is a CLI debugger
inspector

is a web based tool.


pcap binding ncurses

Class: http.Agent
agent.maxSockets agent.sockets agent.requests

Testing/TDD/BDD:
vows

,
mocha

Class: http.ClientRequest
Event 'response' Event: 'socket' Event: 'connect' Event: 'upgrade' Event: 'continue' request.write(chunk, [encoding] ) request.end([data], [encoding]) request.abort() request.setTimeout(timeout, [ca llback]) request.setNoDelay([noDelay]) request.setSocketKeepAlive([e nable], [initialDelay])

d, [message]) assert.deepEqual(actual, expec ted, [message]) assert.notDeepEqual(actual, ex pected, [message]) assert.strictEqual(actual, expec ted, [message]) assert.notStrictEqual(actual, ex pected, [message]) assert.throws(block, [error], [me ssage]) assert.doesNotThrow(block, [er ror], [message]) assert.ifError(value)

Debugger
Watchers Commands reference Stepping Breakpoints Info Execution control Various Advanced Usage

,
mjsunit.runner

Cluster
How It Works cluster.settings cluster.isMaster cluster.isWorker Event: 'fork' Event: 'online' Event: 'listening' Event: 'disconnect' Event: 'exit' Event: 'setup' cluster.setupMaster([settings]) cluster.fork([env]) cluster.settings cluster.disconnect([callback]) cluster.workers Class: Worker worker.id worker.process worker.suicide worker.send(message, [sendHa ndle]) worker.destroy() worker.disconnect() Event: 'message' Event: 'online' Event: 'listening' Event: 'disconnect' Event: 'exit'

http.ClientResponse
Event: 'data' Event: 'end' Event: 'close' response.statusCode response.httpVersion response.headers response.trailers response.setEncoding([encodin g]) response.pause() response.resume()

HTTPS
Class: https.Server https.createServer(options, [re questListener]) https.request(options, callback) https.get(options, callback) Class: https.Agent https.globalAgent

URL
url.parse(urlStr, [parseQueryStr ing], [slashesDenoteHost]) url.format(urlObj) url.resolve(from, to)

overapi.com/nodejs/

3/3

You might also like