\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{raffi001} \pdfinfo{ /Title (nodejs.pdf) /Creator (Cheatography) /Author (raffi001) /Subject (Nodejs Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{C2C2C2} \definecolor{LightBackground}{HTML}{F7F7F7} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Nodejs Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{raffi001} via \textcolor{DarkBackground}{\uline{cheatography.com/41042/cs/12495/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}raffi001 \\ \uline{cheatography.com/raffi001} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Published 14th August, 2017.\\ Updated 14th August, 2017.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{3} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Server Example}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const http = require('http'); \newline \newline const hostname = '127.0.0.1'; \newline const port = 3000; \newline \newline const server = http.createServer((req, res) =\textgreater{} \{ \newline res.statusCode = 200; \newline \seqsplit{res.setHeader('Content-Type'}, 'text/plain'); \newline res.end('Hello World\textbackslash{}n'); \newline \}); \newline \newline server.listen(port, hostname, () =\textgreater{} \{ \newline console.log(`Server running at http://\$\{hostname\}:\$\{port\}/`); \newline \});} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Cluster}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const cluster = require('cluster'); \newline const http = require('http'); \newline const numCPUs = \seqsplit{require('os').cpus().length;} \newline \newline if (cluster.isMaster) \{ \newline console.log(`Master \$\{process.pid\} is running`); \newline \newline // Fork workers. \newline for (let i = 0; i \textless{} numCPUs; i++) \{ \newline cluster.fork(); \newline \} \newline \newline cluster.on('exit', (worker, code, signal) =\textgreater{} \{ \newline console.log(`worker \$\{worker.process.pid\} died`); \newline \}); \newline \} else \{ \newline // Workers can share any TCP connection \newline // In this case it is an HTTP server \newline http.createServer((req, res) =\textgreater{} \{ \newline res.writeHead(200); \newline res.end('hello world\textbackslash{}n'); \newline \}).listen(8000); \newline \newline console.log(`Worker \$\{process.pid\} started`); \newline \}} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{A single instance of Node.js runs in a single thread. To take advantage of multi-core systems the user will sometimes want to launch a cluster of Node.js processes to handle the load. \newline \newline The cluster module allows you to easily create child processes that all share server ports.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{DNS}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const dns = require('dns'); \newline \newline dns.lookup('nodejs.org', (err, addresses, family) =\textgreater{} \{ \newline console.log('addresses:', addresses); \newline \}); \newline \newline \newline const dns = require('dns'); \newline \newline dns.resolve4('archive.org', (err, addresses) =\textgreater{} \{ \newline if (err) throw err; \newline \newline console.log(`addresses: \$\{JSON.stringify(addresses)\}`); \newline \newline addresses.forEach((a) =\textgreater{} \{ \newline dns.reverse(a, (err, hostnames) =\textgreater{} \{ \newline if (err) \{ \newline throw err; \newline \} \newline console.log(`reverse for \$\{a\}: \$\{JSON.stringify(hostnames)\}`); \newline \}); \newline \}); \newline \});} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.53827 cm} x{2.43873 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Globals}} \tn % Row 0 \SetRowColor{LightBackground} \_\_dirname & \_\_filename \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \seqsplit{clearImmediate(immediateObject)} & \seqsplit{clearInterval(intervalObject)} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} \seqsplit{clearTimeout(timeoutObject)} & console \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} exports & global \tn % Row Count 6 (+ 1) % Row 4 \SetRowColor{LightBackground} module & process \tn % Row Count 7 (+ 1) % Row 5 \SetRowColor{white} require() & require.cache \tn % Row Count 8 (+ 1) % Row 6 \SetRowColor{LightBackground} require.resolve() & setImmediate(callback{[}, ...args{]}) \tn % Row Count 10 (+ 2) % Row 7 \SetRowColor{white} \seqsplit{setInterval(callback}, delay{[}, ...args{]}) & \seqsplit{setTimeout(callback}, delay{[}, ...args{]}) \tn % Row Count 12 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Query String}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const querystring = require('querystring'); \newline \newline querystring.parse('w=\%D6\%D0\%CE\%C4\&foo=bar', null, null, \newline \{ decodeURIComponent: gbkDecodeURIComponent \}); \newline \newline querystring.stringify(\{ foo: 'bar', baz: {[}'qux', 'quux'{]}, corge: '' \});} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Assert}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const assert = require('assert'); \newline \newline const obj1 = \{ \newline a: \{ \newline b: 1 \newline \} \newline \}; \newline const obj2 = \{ \newline a: \{ \newline b: 2 \newline \} \newline \}; \newline const obj3 = \{ \newline a: \{ \newline b: 1 \newline \} \newline \}; \newline const obj4 = Object.create(obj1); \newline \newline assert.deepEqual(obj1, obj1); \newline // OK, object is equal to itself \newline \newline assert.deepEqual(obj1, obj2); \newline // AssertionError: \{ a: \{ b: 1 \} \} deepEqual \{ a: \{ b: 2 \} \} \newline // values of b are different \newline \newline assert.deepEqual(obj1, obj3); \newline // OK, objects are equal \newline \newline assert.deepEqual(obj1, obj4); \newline // AssertionError: \{ a: \{ b: 1 \} \} deepEqual \{\} \newline // Prototypes are ignored} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Console}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const out = getStreamSomehow(); \newline const err = getStreamSomehow(); \newline const myConsole = new console.Console(out, err); \newline \newline myConsole.log('hello world'); \newline // Prints: hello world, to out \newline myConsole.log('hello \%s', 'world'); \newline // Prints: hello world, to out \newline myConsole.error(new Error('Whoops, something bad happened')); \newline // Prints: {[}Error: Whoops, something bad happened{]}, to err \newline \newline const name = 'Will Robinson'; \newline myConsole.warn(`Danger \$\{name\}! Danger!`); \newline // Prints: Danger Will Robinson! Danger!, to err} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{eRROR}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{try \{ \newline const m = 1; \newline const n = m + z; \newline \} catch (err) \{ \newline // Handle the error here. \newline \} \newline \newline \newline \newline \newline const fs = require('fs'); \newline fs.readFile('a file that does not exist', (err, data) =\textgreater{} \{ \newline if (err) \{ \newline console.error('There was an error reading the file!', err); \newline return; \newline \} \newline // Otherwise handle the data \newline \}); \newline \newline \newline const net = require('net'); \newline const connection = \seqsplit{net.connect('localhost');} \newline \newline // Adding an 'error' event handler to a stream: \newline connection.on('error', (err) =\textgreater{} \{ \newline // If the connection is reset by the server, or if it can't \newline // connect at all, or on any sort of error encountered by \newline // the connection, the error will be sent here. \newline console.error(err); \newline \}); \newline \newline connection.pipe(process.stdout);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{http}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const http = require('http'); \newline const keepAliveAgent = new http.Agent(\{ keepAlive: true \}); \newline options.agent = keepAliveAgent; \newline http.request(options, onResponseCallback); \newline \newline \newline http.get(\{ \newline hostname: 'localhost', \newline port: 80, \newline path: '/', \newline agent: false // create a new agent just for this one request \newline \}, (res) =\textgreater{} \{ \newline // Do stuff with response \newline \});} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Readline}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const readline = require('readline'); \newline \newline const rl = readline.createInterface(\{ \newline input: process.stdin, \newline output: process.stdout \newline \}); \newline \newline rl.question('What do you think of Node.js? ', (answer) =\textgreater{} \{ \newline // TODO: Log the answer in a database \newline console.log(`Thank you for your valuable feedback: \$\{answer\}`); \newline \newline rl.close(); \newline \});} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Buffer}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{// Creates a zero-filled Buffer of length 10. \newline const buf1 = Buffer.alloc(10); \newline \newline // Creates a Buffer of length 10, filled with 0x1. \newline const buf2 = Buffer.alloc(10, 1); \newline \newline // Creates an uninitialized buffer of length 10. \newline // This is faster than calling Buffer.alloc() but the returned \newline // Buffer instance might contain old data that needs to be \newline // overwritten using either fill() or write(). \newline const buf3 = Buffer.allocUnsafe(10); \newline \newline // Creates a Buffer containing {[}0x1, 0x2, 0x3{]}. \newline const buf4 = Buffer.from({[}1, 2, 3{]}); \newline \newline // Creates a Buffer containing UTF-8 bytes {[}0x74, 0xc3, 0xa9, 0x73, 0x74{]}. \newline const buf5 = Buffer.from('tést'); \newline \newline // Creates a Buffer containing Latin-1 bytes {[}0x74, 0xe9, 0x73, 0x74{]}. \newline const buf6 = Buffer.from('tést', 'latin1');} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Events}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const myEmitter = new MyEmitter(); \newline myEmitter.on('event', function(a, b) \{ \newline console.log(a, b, this); \newline // Prints: \newline // a b MyEmitter \{ \newline // domain: null, \newline // \_events: \{ event: {[}Function{]} \}, \newline // \_eventsCount: 1, \newline // \_maxListeners: undefined \} \newline \}); \newline myEmitter.emit('event', 'a', 'b');} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{File System}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{fs.open('myfile', 'wx', (err, fd) =\textgreater{} \{ \newline if (err) \{ \newline if (err.code === 'EEXIST') \{ \newline console.error('myfile already exists'); \newline return; \newline \} \newline \newline throw err; \newline \} \newline \newline writeMyData(fd); \newline \}); \newline \newline \newline fs.watch('./tmp', \{encoding: 'buffer'\}, (eventType, filename) =\textgreater{} \{ \newline if (filename) \newline console.log(filename); \newline // Prints: \textless{}Buffer ...\textgreater{} \newline \});} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{https}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{// curl -k https://localhost:8000/ \newline const https = require('https'); \newline const fs = require('fs'); \newline \newline const options = \{ \newline key: \seqsplit{fs.readFileSync('test/fixtures/keys/agent2-key.pem')}, \newline cert: \seqsplit{fs.readFileSync('test/fixtures/keys/agent2-cert.pem')} \newline \}; \newline \newline https.createServer(options, (req, res) =\textgreater{} \{ \newline res.writeHead(200); \newline res.end('hello world\textbackslash{}n'); \newline \}).listen(8000);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Stream}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const http = require('http'); \newline \newline const server = http.createServer((req, res) =\textgreater{} \{ \newline // req is an http.IncomingMessage, which is a Readable Stream \newline // res is an http.ServerResponse, which is a Writable Stream \newline \newline let body = ''; \newline // Get the data as utf8 strings. \newline // If an encoding is not set, Buffer objects will be received. \newline req.setEncoding('utf8'); \newline \newline // Readable streams emit 'data' events once a listener is added \newline req.on('data', (chunk) =\textgreater{} \{ \newline body += chunk; \newline \}); \newline \newline // the end event indicates that the entire body has been received \newline req.on('end', () =\textgreater{} \{ \newline try \{ \newline const data = JSON.parse(body); \newline // write back something interesting to the user: \newline res.write(typeof data); \newline res.end(); \newline \} catch (er) \{ \newline // uh oh! bad json! \newline res.statusCode = 400; \newline return res.end(`error: \$\{er.message\}`); \newline \} \newline \}); \newline \}); \newline \newline server.listen(1337);} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Child Process}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{const spawn = \seqsplit{require('child\_process')}.spawn; \newline const ls = spawn('ls', {[}'-lh', '/usr'{]}); \newline \newline ls.stdout.on('data', (data) =\textgreater{} \{ \newline console.log(`stdout: \$\{data\}`); \newline \}); \newline \newline ls.stderr.on('data', (data) =\textgreater{} \{ \newline console.log(`stderr: \$\{data\}`); \newline \}); \newline \newline ls.on('close', (code) =\textgreater{} \{ \newline console.log(`child process exited with code \$\{code\}`); \newline \});} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{The child\_process.spawn() method spawns the child process asynchronously, without blocking the Node.js event loop. The \seqsplit{child\_process.spawnSync()} function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}