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

Camilo Herbert - Node Cheatsheet

This document provides a cheat sheet overview of common Node.js concepts including basic web servers, timers, events, file system operations, HTTP requests, and the fs.Stats object. It lists common Node.js modules like http, fs, and core functions for creating servers, reading/writing files, handling timers and events, making HTTP requests, and accessing metadata about files with fs.Stats. The cheat sheet is intended to serve as a quick reference for common Node tasks and concepts.

Uploaded by

Philippe ARRAS
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)
7 views

Camilo Herbert - Node Cheatsheet

This document provides a cheat sheet overview of common Node.js concepts including basic web servers, timers, events, file system operations, HTTP requests, and the fs.Stats object. It lists common Node.js modules like http, fs, and core functions for creating servers, reading/writing files, handling timers and events, making HTTP requests, and accessing metadata about files with fs.Stats. The cheat sheet is intended to serve as a quick reference for common Node tasks and concepts.

Uploaded by

Philippe ARRAS
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/ 6

Node Cheatsheet Cheat Sheet

by camilo.herbert via cheatography.com/66323/cs/16551/

Basic Webserver example Timers (cont) Events (cont)

var http = require('http'); Allow you to create a timer that is emit​ter.li​ste​ner​s(e​ven​t);


http.c​rea​teS​erv​er(​fun​ction active but if it is the only item Execute each of the listeners in
(request, response) { left in the event loop, node won't order with the supplied arguments.
​ ​res​pon​se.w​ri​teH​ead​(200, keep the program running. Returns true if event had
{'Cont​ent​-Type': 'text/​pla​in'}); unre​f(); listeners, false otherwise.
​ ​res​pon​se.e​nd​('Hello World\n'); If you had previously unref()d a emit​ter.em​it(​event, [arg1], [arg2],
}).lis​ten​(8124); timer you can call ref() to [...]);
consol​e.l​og(​'Server running at explicitly request the timer hold Return the number of listeners for
http:/​/12​7.0.0.1​:8​124/'); the program open. a given event.
ref(); Even​tEm​itt​er.l​is​ten​erC​oun​t(e​mitter,
Timers event);
Events
To schedule execution of a one-time
File system
callback after delay milliseconds. Adds a listener to the end of the
Optionally you can also pass listeners array for the specified Write buffer to the file specified
arguments to the callback. event. by fd.
setT​ime​out​(ca​llback, delay, [arg], emit​ter.ad​dLi​ste​ner​(event, fs.w​rit​e(fd, buffer, offset,
[...]); listener); length, position, callba​ck);
Stop a timer that was previously Same as emitte​r.a​ddL​ist​ener(). Synchr​onous version of fs.wri​te().
created with setTim​eout(). emit​ter.on​(event, listen​er); Returns the number of bytes
clea​rTi​meo​ut(​t); Adds a one time listener for the written.
To schedule the repeated execution event. This listener is invoked fs.w​rit​eSy​nc(fd, buffer, offset,
of callback every delay only the next time the event is length, positi​on);
millis​econds. Optionally you can fired, after which it is removed. Read data from the file specified
also pass arguments to the emit​ter.on​ce(​event, listen​er); by fd.
callback. Remove a listener from the listener fs.r​ead(fd, buffer, offset, length,
setI​nte​rva​l(c​all​back, delay, [arg], array for the specified event. position, callba​ck);
[...]); emit​ter.re​mov​eLi​ste​ner​(event, Synchr​onous version of fs.read.
Stop a timer that was previously listen​er); Returns the number of bytesRead.
created with setInt​erv​al(). Removes all listeners, or those of fs.r​ead​Syn​c(fd, buffer, offset,
clea​rIn​ter​val​(t); the specified event. length, positi​on);
To schedule the "​imm​edi​ate​" emit​ter.re​mov​eAl​lLi​ste​ner​s([​eve​nt]) Asynch​ron​ously reads the entire
execution of callback after I/O ; contents of a file.
events callbacks and before By default EventE​mitters will print fs.r​ead​Fil​e(f​ile​name, [options],
setTimeout and setInt​erval. a warning if more than 10 listeners callba​ck);
setI​mme​dia​te(​cal​lback, [arg], are added for a particular event. Synchr​onous version of
[...]); emit​ter.se​tMa​xLi​ste​ner​s(n); fs.rea​dFile. Returns the contents
Stop a timer that was previously Returns an array of listeners for of the filename. If the encoding
created with setImm​edi​ate(). the specified event. option is specified then this
clea​rIm​med​iat​e(i​mme​dia​teO​bject); function returns a string.
Otherwise it returns a buffer.
fs.r​ead​Fil​eSy​nc(​fil​ename,
[optio​ns]);

By camilo.herbert Not published yet. Sponsored by Readability-Score.com


cheatography.com/camilo- Last updated 3rd August, 2018. Measure your website readability!
herbert/ Page 1 of 6. https://readability-score.com
Node Cheatsheet Cheat Sheet
by camilo.herbert via cheatography.com/66323/cs/16551/

File system (cont) File system (cont) HTTP - Requests (cont)

Asynch​ron​ously writes data to a fs.Stats: objects returned from requ​est.se​tSo​cke​tKe​epA​liv​e([​ena​ble]


file, replacing the file if it fs.stat(), fs.lstat() and , [initi​alD​ela​y]);
already exists. data can be a fs.fstat() and their synchr​onous Emitted when a response is received
string or a buffer. counte​rparts are of this type. to this request. This event is
fs.w​rit​eFi​le(​fil​ename, data, stat​s.i​sFi​le(); emitted only once.
[options], callba​ck); stat​s.i​sDi​rec​tor​y() requ​est.on​('r​esp​onse',
The synchr​onous version of stat​s.i​sBl​ock​Dev​ice() functi​on(​res​ponse) { });
fs.wri​teFile. stat​s.i​sCh​ara​cte​rDe​vic​e() Emitted after a socket is assigned
fs.w​rit​eFi​leS​ync​(fi​lename, data, stat​s.i​sSy​mbo​lic​Lin​k() // (only to this request.
[optio​ns]); valid with fs.lst​at()) requ​est.on​('s​ocket',
Asynch​ron​ously append data to a stat​s.i​sFI​FO() functi​on(​socket) { });
file, creating the file if it not stat​s.i​sSo​cke​t() Emitted each time a server
yet exists. data can be a string or Returns a new ReadStream object. responds to a request with a
a buffer. fs.c​rea​teR​ead​Str​eam​(path, CONNECT method. If this event isn't
fs.a​ppe​ndF​ile​(fi​lename, data, [optio​ns]); being listened for, clients
[options], callba​ck); receiving a CONNECT method will
The synchr​onous version of HTTP - Requests have their connec​tions closed.
fs.app​end​File. requ​est.on​('c​onn​ect',
Sends a chunk of the body.
fs.a​ppe​ndF​ile​Syn​c(f​ile​name, data, functi​on(​res​ponse, socket, head) {
requ​est.wr​ite​(chunk, [encod​ing​]);
[optio​ns]); });
Finishes sending the request. If
Watch for changes on filename, Emitted each time a server
any parts of the body are unsent,
where filename is either a file or responds to a request with an
it will flush them to the stream.
a directory. The returned object is upgrade. If this event isn't being
requ​est.en​d([​data], [encod​ing​]);
a fs.FSW​atcher. The listener listened for, clients receiving an
Aborts a request.
callback gets two arguments (event, upgrade header will have their
requ​est.ab​ort​();
filename). event is either 'rename' connec​tions closed.
Once a socket is assigned to this
or 'change', and filename is the requ​est.on​('u​pgr​ade',
request and is connected
name of the file which triggered functi​on(​res​ponse, socket, head) {
socket.se​tTi​meout() will be called.
the event. });
requ​est.se​tTi​meo​ut(​tim​eout,
fs.w​atc​h(f​ile​name, [options], Emitted when the server sends a
[callb​ack​]);
[liste​ner​]); '100 Continue' HTTP response,
Once a socket is assigned to this
Test whether or not the given path usually because the request
request and is connected
exists by checking with the file contained 'Expect: 100-co​nti​nue'.
socket.se​tNo​Delay() will be called.
system. Then call the callback This is an instru​ction that the
requ​est.se​tNo​Del​ay(​[no​Del​ay]);
argument with either true or false. client should send the request
Once a socket is assigned to this
(should not be used) body.
request and is connected
fs.e​xis​ts(​path, callba​ck); requ​est.on​('c​ont​inue', function()
socket.se​tKe​epA​live() will be
Synchr​onous version of fs.exists. { });
called.
(should not be used)
fs.e​xis​tsS​ync​(pa​th);

By camilo.herbert Not published yet. Sponsored by Readability-Score.com


cheatography.com/camilo- Last updated 3rd August, 2018. Measure your website readability!
herbert/ Page 2 of 6. https://readability-score.com
Node Cheatsheet Cheat Sheet
by camilo.herbert via cheatography.com/66323/cs/16551/

Global Objects Modules (cont) Stream - Writable (cont)

The filename of the code being modu​le.f​il​ena​me; If a writab​le.w​ri​te(​chunk) call


executed. (absolute path) Whether or not the module is done returns false, then the drain
__fi​lename; loading, or is in the process of event will indicate when it is
The name of the directory that the loading. approp​riate to begin writing more
currently executing script resides modu​le.l​oa​ded; data to the stream.
in. (absolute path) The module that required this one. writ​er.o​nc​e('​drain', write);
__di​rna​me; modu​le.p​ar​ent; Call this method when no more data
A reference to the current module. The module objects required by this will be written to the stream.
In particular module.ex​ports is one. writ​abl​e.e​nd(​[ch​unk], [encod​ing],
used for defining what a module modu​le.c​hi​ldr​en; [callb​ack​]);
exports and makes available through export​s.area = function (r) { When the end() method has been
require(). ​ ​return Math.PI r r; called, and all data has been
modu​le; }; flushed to the underlying system,
A reference to the module.ex​ports If you want the root of your this event is emitted.
that is shorter to type. module's export to be a function writ​er.o​n(​'fi​nish', function() {});
expo​rts; (such as a constr​uctor) This is emitted whenever the pipe()
The process object is a global or if you want to export a complete method is called on a readable
object and can be accessed from object in one assignment instead of stream, adding this writable to its
anywhere. It is an instance of building it one property at a time, set of destin​ations.
EventE​mitter. assign it to module.ex​ports instead writ​er.o​n(​'pipe', functi​on(src)
proc​ess; of exports. {});
The Buffer class is a global type module.ex​ports = functi​on(​width) { This is emitted whenever the
for dealing with binary data ​ ​return { unpipe() method is called on a
directly. ​ ​ ​ ​area: function() { readable stream, removing this
Buff​er; ​ ​ ​ ​ ​ ​return width * width; writable from its set of
​ ​ ​ } destin​ations.
Modules ​ }; writ​er.o​n(​'un​pipe', functi​on(src)
} {});
Loads the module module.js in the
Emitted if there was an error when
same directory.
Stream - Writable writing or piping data.
var module =
writ​er.o​n(​'er​ror', functi​on(src)
requir​e('./m​odu​le.j​s'); var writer =
{});
load anothe​r_m​odule as if require() getWritableStreamSomehow();
was called from the module itself. This method writes some data to the
Path
modu​le.r​eq​uir​e('./a​not​her​_mo​dul​e.j​s underlying system, and calls the
'); supplied callback once the data has Normalize a string path, taking
The identifier for the module. been fully handled. care of '..' and '.' parts.
Typically this is the fully writ​abl​e.w​rit​e(c​hunk, [encod​ing], path.no​rma​liz​e(p);
resolved filename. [callb​ack​]); Join all arguments together and
modu​le.i​d; normalize the resulting path.
The fully resolved filename to the path.jo​in(​[pa​th1], [path2], [...]);
module. Resolves 'to' to an absolute path.

By camilo.herbert Not published yet. Sponsored by Readability-Score.com


cheatography.com/camilo- Last updated 3rd August, 2018. Measure your website readability!
herbert/ Page 3 of 6. https://readability-score.com
Node Cheatsheet Cheat Sheet
by camilo.herbert via cheatography.com/66323/cs/16551/

Path (cont) HTTP - Server Events (cont) HTTP - Responses (cont)

path.re​sol​ve(​[from ...], to); Emitted each time a client Sets a single header value for
Solve the relative path from 'from' requests a http CONNECT method. implicit headers. If this header
to 'to'. serv​er.o​n(​'co​nnect', function already exists in the to-be-sent
path.re​lat​ive​(from, to); (request, socket, head) { }); headers, its value will be
Return the directory name of a Emitted each time a client replaced. Use an array of strings
path. Similar to the Unix dirname requests a http upgrade. here if you need to send multiple
command. serv​er.o​n(​'up​grade', function headers with the same name.
path.di​rna​me(​p); (request, socket, head) { }); resp​ons​e.s​etH​ead​er(​name, value);
Return the last portion of a path. If a client connection emits an Reads out a header that's already
Similar to the Unix basename 'error' event - it will forwarded been queued but not sent to the
command. here. client. Note that the name is case
path.ba​sen​ame(p, [ext]); serv​er.o​n(​'cl​ien​tEr​ror', function insens​itive.
Return the extension of the path, (excep​tion, socket) { }); resp​ons​e.g​etH​ead​er(​nam​e);
from the last '.' to end of string Removes a header that's queued for
in the last portion of the path. HTTP - Responses implicit sending.
path.ex​tna​me(​p); resp​ons​e.r​emo​veH​ead​er(​nam​e);
This sends a chunk of the response
The platfo​rm-​spe​cific file This method adds HTTP trailing
body. If this merthod is called and
separator. '\\' or '/'. headers (a header but at the end of
response.writeHead() has not been
path.sep; the message) to the response.
called, it will switch to implicit
The platfo​rm-​spe​cific path resp​ons​e.a​ddT​rai​ler​s(h​ead​ers);
header mode and flush the implicit
delimiter, ';' or ':'. This method signals to the server
headers.
path.de​lim​iter; that all of the response headers
resp​ons​e.w​rit​e(c​hunk, [encod​ing​]);
and body have been sent; that
Sends a HTTP/1.1 100 Continue
HTTP - Server Events server should consider this message
message to the client, indicating
complete. The method,
Emitted each time there is a that the request body should be
respon​se.e​nd(), MUST be called on
request. sent.
each response.
serv​er.o​n(​'re​quest', function resp​ons​e.w​rit​eCo​nti​nue​();
resp​ons​e.e​nd(​[data], [encod​ing​]);
(request, response) { }); Sends a response header to the
When using implicit headers (not
When a new TCP stream is request.
calling respon​se.w​ri​teH​ead()
establ​ished. resp​ons​e.w​rit​eHe​ad(​sta​tus​Code,
explic​itly), this property controls
serv​er.o​n(​'co​nne​ction', function [reaso​nPh​rase], [heade​rs]);
the status code that will be sent
(socket) { }); Sets the Socket's timeout value to
to the client when
Emitted when the server closes. msecs. If a callback is provided,
the headers get flushed.
serv​er.o​n(​'cl​ose', function () { then it is added as a listener on
resp​ons​e.s​tat​usC​ode;
}); the 'timeout' event on the response
Boolean (read-​only). True if
Emitted each time a request with an object.
headers were sent, false
http Expect: 100-co​ntinue is resp​ons​e.s​etT​ime​out​(msecs,
otherwise.
received. callba​ck);
resp​ons​e.h​ead​ers​Sent;
serv​er.o​n(​'ch​eck​Con​tinue', function
(request, response) { });

By camilo.herbert Not published yet. Sponsored by Readability-Score.com


cheatography.com/camilo- Last updated 3rd August, 2018. Measure your website readability!
herbert/ Page 4 of 6. https://readability-score.com
Node Cheatsheet Cheat Sheet
by camilo.herbert via cheatography.com/66323/cs/16551/

HTTP - Responses (cont) Console (cont) Stream - Readable

When true, the Date header will be Same as assert.ok() where if the var readable =
automa​tically generated and sent in expression evaluates as false throw getReadableStreamSomehow();
the response if it is not already an Assert​ion​Error with message. When a chunk of data can be read
present in the headers. Defaults to cons​ole.as​ser​t(e​xpr​ession, from the stream, it will emit a
true. [messa​ge]); 'readable' event.
resp​ons​e.s​end​Date; read​abl​e.o​n('​rea​dable', function()
Indicates that the underlying Process {});
connection was terminated before If you attach a data event
respon​se.e​nd() was called or able listener, then it will switch the
Emitted when the process is about
to flush. stream into flowing mode, and data
to exit
resp​ons​e.o​n('​close', function () { will be passed to your handler as
proc​ess.on​('e​xit', functi​on(​code)
}); soon as it is available.
{});
Emitted when the response has been read​abl​e.o​n('​data',
Emitted when an exception bubbles
sent. functi​on(​chunk) {});
all the way back to the event loop.
resp​ons​e.o​n('​fin​ish', function() { This event fires when there will be
(should not be used)
}); no more data to read.
proc​ess.on​('u​nca​ugh​tEx​cep​tion',
read​abl​e.o​n('​end', function() {});
functi​on(err) {});
Console Emitted when the underlying
A writable stream to stdout.
resource (for example, the backing
Prints to stdout with newline. proc​ess.st​dout;
file descri​ptor) has been closed.
cons​ole.lo​g([​data], [...]); A writable stream to stderr.
Not all streams will emit this.
Same as consol​e.log. proc​ess.st​derr;
read​abl​e.o​n('​close', function()
cons​ole.in​fo(​[data], [...]); A readable stream for stdin.
{});
Same as consol​e.log but prints to proc​ess.stdin;
Emitted if there was an error
stderr. An array containing the command
receiving data.
cons​ole.er​ror​([d​ata], [...]); line arguments.
read​abl​e.o​n('​error', function()
Same as consol​e.e​rror. proc​ess.argv;
{});
cons​ole.wa​rn(​[data], [...]); An object containing the user
The read() method pulls some data
Uses util.i​nspect on obj and prints enviro​nment.
out of the internal buffer and
resulting string to stdout. proc​ess.env;
returns it. If there is no data
cons​ole.di​r(obj); This is the absolute pathname of
available, then it will return
Mark a time. the executable that started the
null.
cons​ole.ti​me(​lab​el); process.
This method should only be called
Finish timer, record output. proc​ess.ex​ecP​ath;
in non-fl​owing mode. In flowin​g-
cons​ole.ti​meE​nd(​lab​el); This is the set of node-s​pecific
mode, this method is called
Print a stack trace to stderr of command line options from the
automa​tically until the internal
the current position. executable that started the
buffer is drained.
cons​ole.tr​ace​(la​bel); process.
read​abl​e.r​ead​([s​ize​]);
proc​ess.ex​ecA​rgv;
Call this function to cause the
stream to return strings of the
specified encoding instead of
Buffer objects.
read​abl​e.s​etE​nco​din​g(e​nco​din​g);

By camilo.herbert Not published yet. Sponsored by Readability-Score.com


cheatography.com/camilo- Last updated 3rd August, 2018. Measure your website readability!
herbert/ Page 5 of 6. https://readability-score.com
Node Cheatsheet Cheat Sheet
by camilo.herbert via cheatography.com/66323/cs/16551/

Stream - Readable (cont) HTTP (cont) HTTP (cont)

This method will cause the readable Set the method to GET and calls serv​er.t​im​eout;
stream to resume emitting data req.end() automa​tic​ally.
events. http.ge​t(o​ptions, [callb​ack​]); HTTP - Messages
read​abl​e.r​esu​me(); Returns a new web server object.
In case of server request, the HTTP
This method will cause a stream in The reques​tLi​stener is a function
version sent by the client. In the
flowin​g-mode to stop emitting data which is automa​tically added to the
case of client response, the HTTP
events. 'request' event.
version of the connected-to server.
read​abl​e.p​aus​e(); server =
mess​age.ht​tpV​ers​ion;
This method pulls all the data out http.c​rea​teS​erv​er(​[re​que​stL​ist​ene​r]
The reques​t/r​esponse headers
of a readable stream, and writes it );
object.
to the supplied destin​ation, Begin accepting connec​tions on the
mess​age.he​ade​rs;
automa​tically managing the flow so specified port and hostname.
The reques​t/r​esponse trailers
that the destin​ation is not serv​er.l​is​ten​(port, [hostn​ame],
object. Only populated after the
overwh​elmed by a fast readable [backlog], [callb​ack​]);
'end' event.
stream. Start a UNIX socket server
mess​age.tr​ail​ers;
read​abl​e.p​ipe​(de​sti​nation, listening for connec​tions on the
The request method as a string.
[optio​ns]); given path.
Read only. Example: 'GET',
This method will remove the hooks serv​er.l​is​ten​(path, [callb​ack​]);
'DELETE'.
set up for a previous pipe() call. The handle object can be set to
mess​age.me​thod;
If the destin​ation is not either a server or socket
Request URL string. This contains
specified, then all pipes are (anything with an underlying
only the URL that is present in the
removed. _handle member), or a {fd: <n>}
actual HTTP request.
read​abl​e.u​npi​pe(​[de​sti​nat​ion​]); object.
mess​age.url;
This is useful in certain cases serv​er.l​is​ten​(ha​ndle, [callb​ack​]);
The 3-digit HTTP response status
where a stream is being consumed by Stops the server from accepting new
code. E.G. 404.
a parser, which needs to connec​tions.
mess​age.st​atu​sCo​de;
"​un-​con​sum​e" some data that it has serv​er.c​lo​se(​[ca​llb​ack​]);
The net.Socket object associated
optimi​sti​cally pulled out of the Sets the timeout value for sockets,
with the connec​tion.
source, so that the stream can be and emits a 'timeout' event on the
mess​age.so​cket;
passed on to some other party. Server object, passing the socket
Calls
read​abl​e.u​nsh​ift​(ch​unk); as an argument, if a timeout
messag​e.c​onn​ect​ion.se​tTi​meo​ut(​msecs
occurs.
, callback).
HTTP serv​er.s​et​Tim​eou​t(m​secs,
mess​age.se​tTi​meo​ut(​msecs,
callba​ck);
A collection of all the standard callba​ck);
Limits maximum incoming headers
HTTP response status codes, and the
count, equal to 1000 by default. If
short description of each.
set to 0 - no limit will be
http.ST​ATU​S_C​ODES;
applied.
This function allows one to
serv​er.m​ax​Hea​der​sCo​unt;
transp​arently issue requests.
The number of millis​econds of
http.re​que​st(​opt​ions, [callb​ack​]);
inactivity before a socket is
presumed to have timed out.

By camilo.herbert Not published yet. Sponsored by Readability-Score.com


cheatography.com/camilo- Last updated 3rd August, 2018. Measure your website readability!
herbert/ Page 6 of 6. https://readability-score.com

You might also like