The Node.js ultimate beginner to pro Cheatsheet in 2021

The Node.js ultimate beginner to pro Cheatsheet in 2021

Many of you guys requested us for NodeJS cheatsheets and here you go guys, this is an ultimate NodeJS cheatsheet.

In programs, the 'high level' scope is the global scope. That implies that in programs in case you're in the global scope 'var' something will characterize a global variable. In Node this is unique. The high level scope isn't the global scope; var inside a Node module will be neighborhood module to that module.

  • __filename - The filename of the code being executed(absolute path)
  • __dirname - The name of the directory that the currently execcuting script resides in(absolute path. )
  • process - The process objecet is a global object and can be accessed from anywhere. It is an instance of Event Emitter.


  • var module = require('./module.js'); - Loads the module.js in same directory.
  • module.require('./another_moude.js'); - Loads another_module as if require() was called frmo the module itself
  •; - The identifier for the module. Typically this is the fully resolved filename
  • module.filename; - The fully resolved filename to the module
  • module.loaded; - Whether or not the module is done loading , or is in the process of loading
  • module.parent; - The module that required this one
  • module.children; - The Module objects required by this one.

Path in NodeJS

Use require('path') to use this module. This module contains utilities for handling and transforming file paths. Almost all these methods perform only string transformation. The file system is not consulted to check whether paths are ValidityState.

  • path.normalize(p); - Normalize a string path, taking care of '..' and '.' parseInt.
  • path.join([path1], [path2], [...]); - Join all arguments together and normalize the resulting path
  • path.resolve([from ...], to); - Solve the relative path from from to to.
  • path.dirname(p); - Return the directory name of a path. Similar to the Unix dirname command.
  • path.basename(p, [ext]); - Return the last portion of a path. Similar to the Unix basename command.
  • path.extname(p); - Return the extension of the path, from the last '.' to end of string in the last portion of the path.
  • path.sep; - The platform-specific file separator. \\ or /
  • path.delimeter; - The platform-specific path delimiter, ';' or ':'.

Process in NodeJS

  • process.on('exit', function(code) {}); - Emitted when the process is about ot exit.
  • process.on('uncaughtException', functiion(err) {}); - Emitted when an exception bubbles all the way back to the event loop
  • process.stdout; - A writable stream to stdout.
  • process.stderr; - A writable stream to stderr.
  • process.stdin; - A readble sream for stdin.
  • process.argv; - An array containing the command line arguments
  • process.env; - An object containing the user environment.
  • process.execPath; - This is the absolute of the executable that started the process.
  • process.execArgv; - This is the set of node-specific command line options form the executable that started the process.
  • process.arch; - What processor architecture you're running on 'arm', 'ia32' or 'x64'
  • process.config; - An object containing the JavaScript representation of the configure options that were used to compile the current node executable.
  •; - The PID of the process
  • process.platform; - What platform you're running on: darwin, freebsd, 'linux', 'sunos' or 'win32'.
  • process.abort(); - This causes node to emit an AbortController. This will cause node to exit and generate a core file.
  • process.chidr(dir); - Changes the current working directory of the prcess or throws an exception if that fails.
  • process.exit([code]); - Ends the process with the specified code. If the omitted, exit uses the 'success' code 0.
  • process.getgid(); - Gets the group identity of the process.
  • process.setgid(id); - Sets the group identity of the process.
  • proces.setuid(id); - Setss the group identity of the process
  • process.getgroups(grps); - Sets the supplementary group IDs.
  • process.kill(pid, [signal]); - Send a signal to a process. pid is the process id and signal is the string describing the signal to send.
  • process.memoryUsaage(); - Returns an object describing the memory usage of the Node process measured in Byte.
  • process.uptime(); - Number of seconds Node has been running

HTTP in NodeJS

To use the HTTP server and client one must require('http').

  • http.STATUS_CODE; - A collection of all the standard HTTP response status codes, and the short description of each
  • http.request(options, [callback]); - This function allows one to transparently issue requests
  • http.get(options, [callback]); - Set the method to GET and calls req.end() automatically
  • server = http.createServer([requestListener]); - Returns a new web server object. The requestListener is a function which is automatically added to the request event
  • server.listen(path, [callback]); - Start a UNIX socket server listening for connections on the given path.
  • server.listen(handle, [callback]); - The handle object an be set to either a server r socket (anything with an underlying _handle member), or a {fd: <n>} object.
  • server.close([callback]); - Stops the server from accepting new connections
  • server.setTimeout(msecs, callback); - Sets the timeout value for sockets and emits a timeout event on the server object, passing the socket as an argument, it a timeout occurs.
  • server.maxHeadersCount; - Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.
  • server.timeout; - The number of milliseconds of inactivity before a socket is presumed to havea timed out
  • server.on('request', function (request, response){}); - Emitted each time there is a request
  • server.on('connection', function (socket) { }); - When a new TCP stream is established
  • server.on('close', function () { }); - Emitted when the server closes
  • server.on('checkContinue', function (request, response) { }); - Emitted eachn time a request with an http Expect: 100-continue is received.
  • server.on('connect', function (request, socket, head) {}); - Emitted each time a client requests a http CONNECT method.
  • server.on('upgrade', function (request, socket, head) {}); - Emitted each time a client requests a http upgrade.
  • server.on('clientError', function (exception, socket) { }); - If a client connection emmits an error event - it will forwarded here
  • request.write(chunk, [encoding]); - Sends a chunk of body
  • request.end([data], [encoding]); - Finishes sending the requests. If any parts of the body are unsent, it will flush them to the stream.
  • requests.abort(); - Aborts are requests
  • request.setTimeout(timeout, [callback]); - Once a socket is assigned to this request and is connect socket.setTimeout(); will be called.
  • request.setNoDelay([noDelay]); - Once a socket is assinged to this request and is connected socket.setNoDelay() will be called
  • request.setSocketKeepAlive([enable], [initiateDelay]); - Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called
  • request.on('socket', function(socket) {}); - Emitted after a soscket is assigned to this request
  • request.on('connect', function(response, socket, head) { }); - Emitted each time a server responds to a request with a CONNECT methods. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.
  • request.on('upgrade', function(response, socket, head) {}); - Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgraded header will have their connections closed
  • response.write(chunk, [encoding]); - This sends a chunk the response body. If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers
  • response.writeHead(statusCode, [reasonPhrase], [headers]); - Sends a response header to the request
  • response.setHeader(name, value); - Sets a single header value for implicit headers. If this headers already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiples headers with the same name.
  • response.removeHeader(name); - Removes a header that's queud for implicit sending
  • reponse.end([data], [encoding]); - This method signals to the server that all of the response headers and body havae been sent; that server should consider this mesage complete. The method, response.end(), methis be called on eaach response.
  • response.statusCode; - When usinsg implicit headers (not calling response.writeHead() explicitly), tis property controls the status code that will be sent to the client when the headers get flushed
  • response.headersSent; - Bolean (read-only). True if headers were sent false otherwise
  • response.sendDate; - When true, the date header will be automatcally generated and sent in the reponse if it is not already present in the headers. Defaults are true.
  • response.on('close', function() {}); - Indicates that the underlying connection was terminated before response.end() was called or able
  • response.on('finish', function() {}) - Emitted when the response has been sent
  • message.httpVersion; - In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected to server
  • message.headers; - The request/response headers object
  • message.trailers; - The request/response trailers object. Only populated after the 'end' event
  • message.method; - The request method as a string. Read only. Example: GET and 'DELETE'.
  • message.url; - Request URL string. This contains only the URL that is present in the actual HTTP request
  • message.statusCode; - The 3 digit HTTP response status code. Ex: 404.
  • message.socket; - The net socket object associated with the connection.
  • message.setTimeout(msecs, callback) - Calls message.connection.setTimeout(msecs, callback) -


This module has utilities for URL resolution and parsing. Call require('url') to use it.

  • url.parse(urlStr, [parseQueryString], [slashesDenoteHost]); - Take a URL string and return an object.
  • url.format(urlObj); - Take a parsed URL object, and return a formatted URL string.
  • url.resolve(from, to); - Take a abse URL, and a href URL and resolve them as a browser would for an anchor tag.

OS in NodeJS

Provides a few basics operating systems related utility funtions. Use require('os') to access this module.

  • os.tmpdir(); - Returns the operating system's default directory for temp files
  • os.hostname(); - Returns the hostname of the operating system
  • os.type(); - Returns the operating system name
  • os.platform(); - Returns the operating system platform
  • os.arch(); - Returns the operating system CPU architecture
  • os.release(); - Returns the operating system release
  • os.uptime(); - Returns the system uptime in seconds
  • os.totalmem(); - Returns the total amount of system memory in bytes
  • os.freemem(); - Returns the total amount of free system memory in bytes
  • os.cpus(); - Returns an array of objects containing information about each CPU/Core installed: model, speed (in mhz), and times (an object containing the number of milliseconds the CPU/code SPENT IN: USER, sys, idle and irq)
  • os.networkInterfaces(); - Get a list of network interfaces

Buffer in NodeJS

Buffer is used to dealing with binary data. Buffer is similar to an arrayn of integers but corresponds to a raw memory allocation outside the V8 heap.

  • Buffer.from(size); - Allocates a new buffer of size octets
  • Buffer.from(array); - Allocates a new buffer using an array of octets
  • Buffer.from(str, [encoding]); - Allocates a new buffer containing the given st. encoding defaults to 'utf8'
  • Buffer.isEncoding(encoding); - Returns true if the encoding is a valid encoding argument or false otherwise
  • Buffer.isBuffer(obj); - Tests if obj is a buffer
  • Buffer.concat(list, [totalLength]); - Returns a buffer which is the result of concatening all the buffers in the list together
  • Buffer.byteLength(string, [encoding]); - Gives the acutal bybte length of string
  • Buffer.toString([encoding], [start], [end]); - Decodes and returns a string from buffer data encoded with encoding (defaults to 'utf8') beginning at start (defaults to 0) and ending at end (defaults to buffer.length)

Assert in NodeJS

This module is used for writing unit tests for your applications, you can access it with require('assert').

  •, expected, message, operator); - Throws an exception that displays the values for actual and expected separated by the provided operator
  • assert(value, message); asset.ok(value, [message]); - Tests id value is truthy, it is equivalent to assert.equal(true, !!value, message).
  • assert.equal(actual, expected, [message]); - Tests shallow, coercive equality with the equal comparison operator ( == ).
  • assert.notEqual(actual, expected, [message]); - Tests shallow, coercive non-quality with the not eual comparison operator
  • assert.deepEqual(actual, expected, [message]); - Tests for deep equality
  • assert.notDeepEqual(actual, expected, [message]); - Tests for any deep inequality
  • assert.strictEqual(actual, expected, [message]); - Tsts strict equality, as determined by the strict equality operator
  • assert.notStrictEqual(actual, expected, [message]); - Tests strict non-quality as determined by the strict not equal operator
  • assert.throws(block, [error], [message]); - Tests strict non-equality as determined by the strict not equal operator
  • assert.doesNotThrow(block, [message]); - Expects block not to throw an error, see assert.throws for details
  • assert.ifError(value); - Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.

Query String

This module provides utilities for dealing with query strings. Call require('querystring') to use it.

  • querystring.stringify(obj, [sep], [eq]); - Serialize an object to a query string. Optinally override the default separator ('&') and assignment ('=') characters.
  • querystring.parse(str, [sep], [eq], [options]); - Deserialize a query string to an object. Optionally override the default separator ('&') and assignment ('=') characters.

We would like thank many people who have contributed this article and the offical NodeJS website, if you have anything to add here please comment it down. If you find any mistakes here please let us know, thanks for reading.