Nodejs Cheat Sheet
by raffi001 via cheatography.com/41042/cs/12495/
Query String Cluster (cont) DNS (cont)
const querystring = } console.log(addresses:
require('querystring'); cluster.on('exit', (worker, code, ${JSON.stringify(addresses)});
querystring.parse('w=%D6%D0%CE%C4& signal) => { addresses.forEach((a) => {
foo=bar', null, null, console.log(worker dns.reverse(a, (err, hostnames)
{ decodeURIComponent: ${worker.process.pid} died); => {
gbkDecodeURIComponent }); }); if (err) {
querystring.stringify({ foo: 'bar', } else { throw err;
baz: ['qux', 'quux'], corge: '' }); // Workers can share any TCP }
connection console.log(reverse for
Server Example // In this case it is an HTTP ${a}:
server ${JSON.stringify(hostnames)});
const http = require('http');
http.createServer((req, res) => { });
const hostname = '127.0.0.1';
res.writeHead(200); });
const port = 3000;
res.end('hello world\n'); });
const server =
}).listen(8000);
http.createServer((req, res) => {
console.log(Worker Globals
res.statusCode = 200;
${process.pid} started);
res.setHeader('Content-Type', __dirname __filename
}
'text/plain'); clearImmediate(imme clearInterval(intervalOb
res.end('Hello World\n'); A single instance of Node.js runs in a single diateObject) ject)
}); thread. To take advantage of multi-core clearTimeout(timeout console
server.listen(port, hostname, () => systems the user will sometimes want to launch Object)
a cluster of Node.js processes to handle the
{ exports global
load.
console.log(Server running at module process
http://${hostname}:${port}/);
The cluster module allows you to easily create require() require.cache
}); child processes that all share server ports.
require.resolve() setImmediate(callback[
, ...args])
Cluster DNS
setInterval(callback, setTimeout(callback,
const cluster = require('cluster'); const dns = require('dns'); delay[, ...args]) delay[, ...args])
const http = require('http'); dns.lookup('nodejs.org', (err,
const numCPUs = addresses, family) => {
require('os').cpus().length; console.log('addresses:',
if (cluster.isMaster) { addresses);
console.log(Master });
${process.pid} is running); const dns = require('dns');
// Fork workers. dns.resolve4('archive.org', (err,
for (let i = 0; i < numCPUs; i++) addresses) => {
{ if (err) throw err;
cluster.fork();
By raffi001 Published 14th August, 2017. Sponsored by CrosswordCheats.com
cheatography.com/raffi001/ Last updated 14th August, 2017. Learn to solve cryptic crosswords!
Page 1 of 4. http://crosswordcheats.com
Nodejs Cheat Sheet
by raffi001 via cheatography.com/41042/cs/12495/
http Assert Console
const http = require('http'); const assert = require('assert'); const out = getStreamSomehow();
const keepAliveAgent = new const obj1 = { const err = getStreamSomehow();
http.Agent({ keepAlive: true }); a: { const myConsole = new
options.agent = keepAliveAgent; b: 1 console.Console(out, err);
http.request(options, } myConsole.log('hello world');
onResponseCallback); }; // Prints: hello world, to out
http.get({ const obj2 = { myConsole.log('hello %s', 'world');
hostname: 'localhost', a: { // Prints: hello world, to out
port: 80, b: 2 myConsole.error(new Error('Whoops,
path: '/', } something bad happened'));
agent: false // create a new }; // Prints: [Error: Whoops,
agent just for this one request const obj3 = { something bad happened], to err
}, (res) => { a: { const name = 'Will Robinson';
// Do stuff with response b: 1 myConsole.warn(Danger ${name}!
}); } Danger!);
}; // Prints: Danger Will Robinson!
Readline const obj4 = Object.create(obj1); Danger!, to err
assert.deepEqual(obj1, obj1);
const readline =
// OK, object is equal to itself eRROR
require('readline');
assert.deepEqual(obj1, obj2);
const rl = try {
// AssertionError: { a: { b: 1 } }
readline.createInterface({ const m = 1;
deepEqual { a: { b: 2 } }
input: process.stdin, const n = m + z;
// values of b are different
output: process.stdout } catch (err) {
assert.deepEqual(obj1, obj3);
}); // Handle the error here.
// OK, objects are equal
rl.question('What do you think of }
assert.deepEqual(obj1, obj4);
Node.js? ', (answer) => { const fs = require('fs');
// AssertionError: { a: { b: 1 } }
// TODO: Log the answer in a fs.readFile('a file that does not
deepEqual {}
database exist', (err, data) => {
// Prototypes are ignored
console.log(Thank you for your if (err) {
valuable feedback: ${answer}); console.error('There was an
rl.close(); error reading the file!', err);
}); return;
}
By raffi001 Published 14th August, 2017. Sponsored by CrosswordCheats.com
cheatography.com/raffi001/ Last updated 14th August, 2017. Learn to solve cryptic crosswords!
Page 2 of 4. http://crosswordcheats.com
Nodejs Cheat Sheet
by raffi001 via cheatography.com/41042/cs/12495/
eRROR (cont) Stream Stream (cont)
// Otherwise handle the data const http = require('http'); });
}); const server = });
const net = require('net'); http.createServer((req, res) => { server.listen(1337);
const connection = // req is an
net.connect('localhost'); http.IncomingMessage, which is a Buffer
// Adding an 'error' event handler Readable Stream
// Creates a zero-filled Buffer of
to a stream: // res is an
length 10.
connection.on('error', (err) => { http.ServerResponse, which is a
const buf1 = Buffer.alloc(10);
// If the connection is reset by Writable Stream
// Creates a Buffer of length 10,
the server, or if it can't let body = '';
filled with 0x1.
// connect at all, or on any sort // Get the data as utf8 strings.
const buf2 = Buffer.alloc(10, 1);
of error encountered by // If an encoding is not set,
// Creates an uninitialized buffer
// the connection, the error will Buffer objects will be received.
of length 10.
be sent here. req.setEncoding('utf8');
// This is faster than calling
console.error(err); // Readable streams emit 'data'
Buffer.alloc() but the returned
}); events once a listener is added
// Buffer instance might contain
connection.pipe(process.stdout); req.on('data', (chunk) => {
old data that needs to be
body += chunk;
// overwritten using either fill()
https });
or write().
// the end event indicates that
// curl -k https://localhost:8000/ const buf3 =
the entire body has been received
const https = require('https'); Buffer.allocUnsafe(10);
req.on('end', () => {
const fs = require('fs'); // Creates a Buffer containing
try {
const options = { [0x1, 0x2, 0x3].
const data =
key: const buf4 = Buffer.from([1, 2,
JSON.parse(body);
fs.readFileSync('test/fixtures/keys 3]);
// write back something
/agent2-key.pem'), // Creates a Buffer containing
interesting to the user:
cert: UTF-8 bytes [0x74, 0xc3, 0xa9,
res.write(typeof data);
fs.readFileSync('test/fixtures/keys 0x73, 0x74].
res.end();
/agent2-cert.pem') const buf5 = Buffer.from('tést');
} catch (er) {
}; // Creates a Buffer containing
// uh oh! bad json!
https.createServer(options, (req, Latin-1 bytes [0x74, 0xe9, 0x73,
res.statusCode = 400;
res) => { 0x74].
return res.end( error:
res.writeHead(200); const buf6 = Buffer.from('tést',
${er.message});
res.end('hello world\n'); 'latin1');
}
}).listen(8000);
Events
const myEmitter = new MyEmitter();
myEmitter.on('event', function(a,
b) {
console.log(a, b, this);
// Prints:
By raffi001 Published 14th August, 2017. Sponsored by CrosswordCheats.com
cheatography.com/raffi001/ Last updated 14th August, 2017. Learn to solve cryptic crosswords!
Page 3 of 4. http://crosswordcheats.com
Nodejs Cheat Sheet
by raffi001 via cheatography.com/41042/cs/12495/
Events (cont) Child Process
// a b MyEmitter { const spawn =
// domain: null, require('child_process').spawn;
// _events: { event: [Function] const ls = spawn('ls', ['-lh',
}, '/usr']);
// _eventsCount: 1, ls.stdout.on('data', (data) => {
// _maxListeners: undefined } console.log(stdout: ${data} );
}); });
myEmitter.emit('event', 'a', 'b'); ls.stderr.on('data', (data) => {
console.log(stderr: ${data} );
File System });
ls.on('close', (code) => {
fs.open('myfile', 'wx', (err, fd)
console.log(child process exited
=> {
with code ${code});
if (err) {
});
if (err.code === 'EEXIST') {
console.error('myfile already The child_process.spawn() method spawns the
exists'); child process asynchronously, without blocking
return; the Node.js event loop. The
child_process.spawnSync() function provides
}
equivalent functionality in a synchronous
throw err;
manner that blocks the event loop until the
}
spawned process either exits or is terminated.
writeMyData(fd);
});
fs.watch('./tmp', {encoding:
'buffer'}, (eventType, filename) =>
{
if (filename)
console.log(filename);
// Prints: <Buffer ...>
});
By raffi001 Published 14th August, 2017. Sponsored by CrosswordCheats.com
cheatography.com/raffi001/ Last updated 14th August, 2017. Learn to solve cryptic crosswords!
Page 4 of 4. http://crosswordcheats.com