node_js_cheatsheet_withLinks_compressed
node_js_cheatsheet_withLinks_compressed
log(systemInfo)
setTimeout(() => {
NodeJS
CHEAT SHEET
// Example paths
What is NodeJS?
It is a runtime environment that allows JavaScript for server-side programming,
enabling the execution of JavaScript code outside of a web browser.
Use case
Architecture
PROCESS
V8 EVENT
(JAVASCRIPT ENGINE) OS LOOP EXECUTE
OPERATION CALLBACK
02 NodeJS Cheatsheet
Working
03 NodeJS Cheatsheet
10.Repeat - The process repeats, allowing
Node.js to efficiently handle multiple
events simultaneously.
Incoming
Requests Event
Loop
Improved App
High Performance
Response Time
Cross-Platform
Caching
Development
Extensibility
04 NodeJS Cheatsheet
Asynchronous
Unstable API
Programming Model
NodeJS Disadvantages
We can install Node.js on MacOS easily by We can install Node.js on Windows easily
using the installer from the official by using the installer from the official
Node.js website. Node.js website.
Linux (Ubuntu
There are various package managers available for each distribution. We can install
Node.js by using the Ubuntu official repository.
Command Comments
05 NodeJS Cheatsheet
03 Global Object in NodeJS
Global object
For example, to have some code execute after 5 seconds we can use either
global.setTimeout or just setTimeout
setTimeout(() => {
console.log('hello');
}, 5000);
Note: It's important to note that while the global object provides accessibility across
modules, relying too heavily on global variables and functions can lead to code that is
harder to maintain and understand. Therefore, it's advisable to use globals judiciously
and consider alternative approaches for better code organization and readability.
06 NodeJS Cheatsheet
04 Process object in NodeJS
A process is the instance of a computer program that is being executed. Node has a
global process object NODE_ENV which can be used to determine the environment in
which the application is running
process.argv in NodeJS
process.argv in NodeJS process.memoryUsage in NodeJS
console.log(process.argv[2]);
// 'testing' will be printed
07 NodeJS Cheatsheet
Node.js and Asynchronous
05 Programming
Async VS Sync
Node.js leverages asynchronous
programming, employing a non-blocking Request 1 Request 1
event-driven architecture with callback
functions, to efficiently handle concurrent Request 2
Response 1
tasks like I/O operations, enhancing
Request 2
scalability and responsiveness. Response 1
Response 2 Response 2
Asynchronous Synchronous
1.Core module
Modules included within the environment to efficiently perform common tasks.
process.argv in NodeJS
console module os module
const os = require('os');
const systemInfo = {
'Home Directory': os.homedir(),
'Operating System': os.type(),
'Last Reboot': os.uptime()
};
// Printing systemInfo
console.log(systemInfo)
08 NodeJS Cheatsheet
Output:
{
'Home Directory': '/home/node',
'Operating System': 'Linux',
'Last Reboot': 1527.03
}
process.argv in NodeJS
util module path
Contains utility functions. Common uses The `path` module in Node.js provides
include runtime type checking with types utilities for working with file and directory
and turning callback functions into paths.
promises with the .promisify() method.
dir base
Output:
09 NodeJS Cheatsheet
process.argv in NodeJS
fs
// Example paths
open rename write read const inputFilePath = 'input.txt';
const outputFilePath = 'output.txt';
Output:
Output:
2. require function
We can re-use existing code by using the Return value of
require(x)
Node built-in require() function. This function
function imports code from another require(x) = module.exports
module.
Module y module.exports Module x
object
const fs = require('fs');
fs.readFileSync('hello.txt');
// OR...
const { readFileSync } = require('fs');
readFileSync('hello.txt');
10 NodeJS Cheatsheet
3. Built-in modules 4. events module
Key built-in modules include: Used for EventEmitter, also has an .emit()
method which announces a named event
• fs → read and write files on your file that has occured.
system 1 2
listener 1 listener 2
• path → combine paths regardless of
which OS you're using invoke invoke
event 1
• process → information about the
get all the listeners for
currently running process, e.g. events/listener eventName and invoke
them sequentially with
object
key/value the args
process.argv for arguments passed in or
process.env for environment variables
emit
• http → make requests and create
HTTP servers eventName args
• events → work with the EventEmitter // Create an instance of the EventEmitter class
let myEmitter = new events.EventEmitter();
let version = (data) => {
• crypto → cryptography tools like console.log(`participant: ${data}.`);
};
11 NodeJS Cheatsheet
5. error module 6. buffer object
It doesnʼt have a specific error module. A Buffer is an object that represents a static
The callback function has an error passed amount of memory that canʼt be resized.
as a first parameter. If there is no error The Buffer class is within the global buffer
then that parameter is undefined. module, meaning it can be used without
the require() statement.
// In src/fileModule.js
exports.read = function read(filename) { }
exports.write = function write(filename, data) { }
12 NodeJS Cheatsheet
9. ECMAScript modules
The imports above use a syntax known as
CommonJS (CJS) modules. Node treats // In src/fileModule.mjs
function read(filename) { }
JavaScript code as CommonJS modules by function write(filename, data) { }
export {
default. More recently, you may have seen read,
write,
the ECMAScript module (ESM) syntax. This };
// In src/sayHello.mjs
is the syntax that is used by TypeScript import { write } from './response.mjs';
write('hello.txt', 'Hello world!');
Extension: .mjs
HTTP messages can be protected using Transort Layer Security (TLS), a protocol
designed to facilitate secure data transmission via encryption.
1. .createServer() Method
• Callback function has two primary // Start server listening on port 8080
server.listen(8080, () => {
const { address, port } = server.address();
arguments; the request (commonly console.log(`Server is listening on: http://${address}:${port}`);
});
13 NodeJS Cheatsheet
2. Request Object 3. Response Object
• Contains information about the • Contains information about the
incoming HTTP request outgoing HTTP response
• Handle server requests such as routing • Contains various properties and
and data processing methods that can be used to configure
and send the response such as
.statusCode, .setHeader(), and.end()
4. url Module
const http = require('http');
http:/www.tutorialkart.com/index.php?type=page
Hostname Search
Pathname
/* Deconstructing a URL */
/* Constructing a URL */
14 NodeJS Cheatsheet
5. Query String 6. Request Body
Parameters
• Used in conjunction with GET requests • Data is commonly provided in the body
to submit information used in of a request
processing a request • The body is most commonly used in
• Provide filter criteria for some requested POST and PUT requests as they usually
data have information that needs to be
processed by the server
http://www.pronteff.com/page.html?parameter1=[@field:fieldname]¶meter2=[@field:fieldname2]
15 NodeJS Cheatsheet
9. HTTP and Databases 10. HTTP and External
APIs
• HTTP requests can be used to interact • Used to interact with other external
with databases to retrieve remote data APIs from within a server
const options = {
hostname: 'example.com',
port: 8080,
path: '/projects',
method: 'GET',
}
'Content-Type': 'application/json'
Status Codes }
16 NodeJS Cheatsheet
08 Packages in NodeJS
A package is a collection of Node modules along with a package.json file describing
the package
1.npm command
Command Comments
17 NodeJS Cheatsheet
2. package.json file 3. node_modules
4. package-lock.json
18 NodeJS Cheatsheet
09 Event emitter in NodeJS
19 NodeJS Cheatsheet
10 Concept of the backend in NodeJS
CRUD
CRUD
HTTP Method Example
Operation
Create POST POST /cards - Save a new card to the cards collection
20 NodeJS Cheatsheet
11 Express.js
POST route
app.post("/cards", (req, res) => {
// Get body from the request
const card = req.body;
// Validate the body
if (!card.value || !card.suit) {
return res.status(400).json({
error: 'Missing required card property',
});
}
// Update your collection
cards.push(card);
// Send saved object in the response to verify
return res.json(card);
});
21 NodeJS Cheatsheet
12 Middlewares in Express
Middleware Stack
next() next()
Request 1 2 3 Response
• Functions that have access to the Functions that can be created to perform
request, response objects, and the specific tasks or validations in the
next function in the applicationʼs request-response cycle, adding customized
request-response cycle, allowing for processing to routes.
pre-processing, modification, or
termination of the request flow based
on specific conditions.
• Enhance the functionality of the server
by adding layers of processing between
the client and the final route handlers
22 NodeJS Cheatsheet
3. Third-Party
Middlewares
Third-party Middlewares in Node.js are
pre-built middleware functions provided by
external libraries, often used to add
common functionality (e.g., authentication,
logging) to an application with minimal
setup
Here's a commonly used and recommended structure for a basic Node.js application.
project-root/
│
├── node_modules/ // Installed npm packages (auto-generated)
├── public/ // Static files (e.g., HTML, CSS, client-side JavaScript)
├── src/ // Source code
│ ├── controllers/ // Route controllers
│ ├── models/ // Data models
│ ├── routes/ // Express route definitions
│ ├── services/ // Business logic and external services
│ ├── utils/ // Utility functions
│ └── app.js // Main application file
│
├── views/ // View templates (if using a templating engine like EJS)
├── .gitignore // Git ignore file
├── package.json // Project metadata and dependencies
├── package-lock.json // Dependency lock file (auto-generated)
├── README.md // Project documentation
└── .env // Environment variables configuration file
23 NodeJS Cheatsheet
14 Cross-origin resource sharing
15 PM2 commands
• PM2 is a tool we use to create and manage Node.js clusters. It allows us to create
clusters of processes, manage those processes in production, and keep our
applications running forever.
• We can install the PM2 tool globally using npm install -g pm2
24 NodeJS Cheatsheet
HTTP Method Example
pm2 start
Start server.js in cluster mode with 4 processes
server.js -i 4
pm2 logs --
Show older logs up to 200 lines long.
lines 200
25 NodeJS Cheatsheet