0% found this document useful (0 votes)
107 views4 pages

Nodejs Cheat Sheet: by Via

The document is a cheat sheet for Node.js that provides summaries of key concepts in Node.js including: query strings, servers, clustering, DNS lookups, assertions, console logging, readline interfaces, and error handling. It contains code examples and explanations for common Node.js modules like http, cluster, dns, assert, console, readline, and fs.

Uploaded by

pbecic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views4 pages

Nodejs Cheat Sheet: by Via

The document is a cheat sheet for Node.js that provides summaries of key concepts in Node.js including: query strings, servers, clustering, DNS lookups, assertions, console logging, readline interfaces, and error handling. It contains code examples and explanations for common Node.js modules like http, cluster, dns, assert, console, readline, and fs.

Uploaded by

pbecic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Nodejs Cheat Sheet

by raffi001 via cheatography.com/41042/cs/12495/

Query String Cluster (cont) DNS (cont)

const querystring = ​ } ​ ​con​sol​e.l​og(​ad​dre​sses:


require('querystring'); ​ ​clu​ste​r.o​n('​exit', (worker, code, ${JSON.st​rin​gif​y(a​ddr​ess​es)});
querys​tri​ng.p​ar​se(​'w=​%D6​%D0​%CE​%C4​& signal) => { ​ ​add​res​ses.fo​rEa​ch((a) => {
f​oo=​bar', null, null, ​ ​ ​ ​con​sol​e.l​og(​worker ​ ​ ​ ​dns.re​ver​se(a, (err, hostnames)
​ { decode​URI​Com​ponent: ${work​er.p​ro​ces​s.pid} died); => {
gbkDec​ode​URI​Com​ponent }); ​ }); ​ ​ ​ ​ ​ if (err) {
querys​tri​ng.s​tr​ing​ify({ foo: 'bar', } else { ​ ​ ​ ​ ​ ​ ​ ​throw err;
baz: ['qux', 'quux'], corge: '' }); ​ // Workers can share any TCP ​ ​ ​ ​ ​ }
connection ​ ​ ​ ​ ​ ​con​sol​e.l​og(​re​verse for
Server Example ​ // In this case it is an HTTP ${a}:
server ${JSON.st​rin​gif​y(h​ost​nam​es)});
const http = require('http');
​ ​htt​p.c​rea​teS​erv​er(​(req, res) => { ​ ​ ​ });
const hostname = '127.0.0.1';
​ ​ ​ ​res.wr​ite​Hea​d(200); ​ });
const port = 3000;
​ ​ ​ ​res.en​d('​hello world\n'); });
const server =
​ ​}).l​is​ten​(8000);
http.c​rea​teS​erv​er(​(req, res) => {
​ ​con​sol​e.l​og(​Worker Globals
​ ​res.st​atu​sCode = 200;
${proc​ess.pid} started);
​ ​res.se​tHe​ade​r('​Con​ten​t-T​ype', __dirname __filename
}
'text/​pla​in'); clearI​mme​dia​te(​imm​e clearI​nte​rva​l(i​nte​rva​lOb​
​ ​res.en​d('​Hello World\n'); A single instance of Node.js runs in a single di​ate​Object) ject)
}); thread. To take advantage of multi-core clearT​ime​out​(ti​meo​ut console
server.li​ste​n(port, hostname, () => systems the user will sometimes want to launch O​bject)
a cluster of Node.js processes to handle the
{ exports global
load.
​ ​con​sol​e.l​og(​Server running at module process
http:/​/${​hos​tna​me}​:${​por​t}/);
The cluster module allows you to easily create require() requir​e.cache
}); child processes that all share server ports.
requir​e.r​eso​lve() setImm​edi​ate​(ca​llb​ack[
, ...args])
Cluster DNS
setInt​erv​al(​cal​lback, setTim​eou​t(c​all​back,
const cluster = require('cluster'); const dns = require('dns'); delay[, ...args]) delay[, ...args])
const http = requir​e('​http'); dns.lo​oku​p('​nod​ejs.org', (err,
const numCPUs = addresses, family) => {
requir​e('​os'​).c​pus​().l​ength; ​ ​con​sol​e.l​og(​'ad​dre​sses:',
if (clust​er.i​sM​aster) { addres​ses);
​ ​con​sol​e.l​og(​Master });
${proc​ess.pid} is running); const dns = requir​e('​dns');
​ // Fork workers. dns.re​sol​ve4​('a​rch​ive.org', (err,
​ for (let i = 0; i < numCPUs; i++) addresses) => {
{ ​ if (err) throw err;
​ ​ ​ ​clu​ste​r.f​ork();

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 keepAl​ive​Agent = new const obj1 = { const err = getStr​eam​Som​ehow();
http.A​gent({ keepAlive: true }); ​ a: { const myConsole = new
option​s.agent = keepAl​ive​Agent; ​ ​ ​ b: 1 consol​e.C​ons​ole​(out, err);
http.r​equ​est​(op​tions, ​ } myCons​ole.lo​g('​hello world');
onResp​ons​eCa​llb​ack); }; // Prints: hello world, to out
http.get({ const obj2 = { myCons​ole.lo​g('​hello %s', 'world');
​ ​hos​tname: 'local​host', ​ a: { // Prints: hello world, to out
​ ​port: 80, ​ ​ ​ b: 2 myCons​ole.er​ror(new Error(​'Wh​oops,
​ ​path: '/', ​ } something bad happen​ed'));
​ ​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 myCons​ole.wa​rn(​Danger ${name}!
}); ​ } Danger!);
}; // Prints: Danger Will Robinson!
Readline const obj4 = Object.cr​eat​e(o​bj1); Danger!, to err
assert.de​epE​qua​l(obj1, obj1);
const readline =
// OK, object is equal to itself eRROR
require('readline');
assert.de​epE​qua​l(obj1, obj2);
const rl = try {
// Assert​ion​Error: { a: { b: 1 } }
readli​ne.c​re​ate​Int​erf​ace({ ​ ​const m = 1;
deepEqual { a: { b: 2 } }
​ ​input: proces​s.s​tdin, ​ ​const n = m + z;
// values of b are different
​ ​output: proces​s.s​tdout } catch (err) {
assert.de​epE​qua​l(obj1, obj3);
}); ​ // Handle the error here.
// OK, objects are equal
rl.que​sti​on(​'What do you think of }
assert.de​epE​qua​l(obj1, obj4);
Node.js? ', (answer) => { const fs = requir​e('​fs');
// Assert​ion​Error: { a: { b: 1 } }
​ // TODO: Log the answer in a ​ ​fs.r​ea​dFi​le('a file that does not
deepEqual {}
database exist', (err, data) => {
// Prototypes are ignored
​ ​con​sol​e.l​og(​Thank you for your ​ ​ ​ if (err) {
valuable feedback: ${answ​er}); ​ ​ ​ ​ ​ ​con​sol​e.e​rro​r('​There was an
​ ​rl.c​lo​se(); 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 = requir​e('​net'); http.c​rea​teS​erv​er(​(req, res) => { server.li​ste​n(1​337);
const connection = ​ // req is an
net.co​nne​ct(​'lo​cal​host'); http.I​nco​min​gMe​ssage, 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.
connec​tio​n.o​n('​error', (err) => { http.S​erv​erR​esp​onse, which is a
const buf1 = Buffer.al​loc​(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.al​loc(10, 1);
of error encoun​tered by ​ // If an encoding is not set,
// Creates an uninit​ialized buffer
​ // the connec​tion, the error will Buffer objects will be received.
of length 10.
be sent here. ​ ​req.se​tEn​cod​ing​('u​tf8');
// This is faster than calling
​ ​con​sol​e.e​rro​r(err); ​ // Readable streams emit 'data'
Buffer.al​loc() but the returned
}); events once a listener is added
// Buffer instance might contain
connec​tio​n.p​ipe​(pr​oce​ss.s​td​out); ​ ​req.on​('d​ata', (chunk) => {
old data that needs to be
​ ​ ​ body += chunk;
// overwr​itten 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 = requir​e('​htt​ps'); Buffer.al​loc​Uns​afe​(10);
​ ​req.on​('end', () => {
const fs = requir​e('​fs'); // Creates a Buffer containing
​ ​ ​ try {
const options = { [0x1, 0x2, 0x3].
​ ​ ​ ​ ​ ​const data =
​ key: const buf4 = Buffer.fr​om([1, 2,
JSON.p​ars​e(b​ody);
fs.rea​dFi​leS​ync​('t​est​/fi​xtu​res​/ke​ys 3]);
​ ​ ​ ​ ​ // write back something
/​age​nt2​-ke​y.p​em'), // Creates a Buffer containing
intere​sting to the user:
​ ​cert: UTF-8 bytes [0x74, 0xc3, 0xa9,
​ ​ ​ ​ ​ ​res.wr​ite​(typeof data);
fs.rea​dFi​leS​ync​('t​est​/fi​xtu​res​/ke​ys 0x73, 0x74].
​ ​ ​ ​ ​ ​res.end();
/​age​nt2​-ce​rt.p​em') const buf5 = Buffer.fr​om(​'té​st');
​ ​ ​ } catch (er) {
}; // Creates a Buffer containing
​ ​ ​ ​ ​ // uh oh! bad json!
https.c​re​ate​Ser​ver​(op​tions, (req, Latin-1 bytes [0x74, 0xe9, 0x73,
​ ​ ​ ​ ​ ​res.st​atu​sCode = 400;
res) => { 0x74].
​ ​ ​ ​ ​ ​return res.en​d( ​error:
​ ​res.wr​ite​Hea​d(200); const buf6 = Buffer.fr​om(​'tést',
${er.m​ess​age});
​ ​res.en​d('​hello world\n'); 'latin1');
​ ​ ​ }
}).lis​ten​(8000);
Events

const myEmitter = new MyEmitter();


myEmit​ter.on​('e​vent', functi​on(a,
b) {
​ ​con​sol​e.l​og(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']);
​ // _event​sCount: 1, ls.std​out.on​('d​ata', (data) => {
​ // _maxLi​ste​ners: undefined } ​ ​con​sol​e.l​og(​st​dout: ${data} );
}); });
myEmit​ter.em​it(​'ev​ent', 'a', 'b'); ls.std​err.on​('d​ata', (data) => {
​ ​con​sol​e.l​og(​st​derr: ${data} );
File System });
ls.on(​'cl​ose', (code) => {
fs.open('myfile', 'wx', (err, fd)
​ ​con​sol​e.l​og(​child process exited
=> {
with code ${code});
​ if (err) {
});
​ ​ ​ if (err.code === 'EEXIST') {
​ ​ ​ ​ ​ ​con​sol​e.e​rro​r('​myfile already The child_​pro​ces​s.s​pawn() method spawns the
exists'); child process asynch​ron​ously, without blocking

​ ​ ​ ​ ​ ​return; the Node.js event loop. The


child_​pro​ces​s.s​paw​nSync() function provides
​ ​ ​ }
equivalent functi​onality in a synchr​onous
​ ​ ​ ​throw err;
manner that blocks the event loop until the
​ }
spawned process either exits or is termin​ated.
​ ​wri​teM​yDa​ta(fd);
});
fs.wat​ch(​'./​tmp', {encoding:
'buffer'}, (event​Type, filename) =>
{
​ if (filename)
​ ​ ​ ​con​sol​e.l​og(​fil​ename);
​ ​ ​ // 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

You might also like