0% found this document useful (0 votes)
207 views17 pages

Node JS Cheat Sheet + PDF Zero To Mastery

This document provides a cheat sheet overview of key concepts and functions in Node.js. It begins with instructions for running Node.js and describes the global object and module system. It then covers Node packages and the package.json file. Other sections explain the EventEmitter, backend concepts, Express.js, folder structure, and useful commands. The document aims to help Node.js developers learn and have a quick reference guide to basics.
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)
207 views17 pages

Node JS Cheat Sheet + PDF Zero To Mastery

This document provides a cheat sheet overview of key concepts and functions in Node.js. It begins with instructions for running Node.js and describes the global object and module system. It then covers Node packages and the package.json file. Other sections explain the EventEmitter, backend concepts, Express.js, folder structure, and useful commands. The document aims to help Node.js developers learn and have a quick reference guide to basics.
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/ 17

Node JS Cheat

Sheet
We created this Node JS Cheat Sheet initially for
students of our Node.js Bootcamp: Complete Node.js
Developer: Zero to Mastery. But we're now sharing it
with any and all Developers that want to learn and
remember some of the key functions and concepts of
Node JS, and have a quick reference guide to the
basics of Node JS.

Want to download a PDF


version of this Node JS
Cheat Sheet?
Enter your email below and we'll
send it to you �

Enter Your Email Address

Unsubscribe anytime.

If you’ve stumbled across this cheatsheet and are just


starting to learn Node.js, you've made a great choice!
Node.js is widly popular amongst developers and
companies alike and is a great skill to learn if you're
interested in becoming a backend developer or a
fullstack developer.

However, if you're stuck in an endless cycle of


YouTube tutorials and want to start building real world
projects, become a professional backend (or
fullstack) developer, have fun and actually get hired,
then come join the Zero To Mastery Academy. You'll
learn Node.js from actual industry professionals
alongside thousands of students in our private
Discord community.

You'll not only learn to become a top 10% Node


Developer by learning advanced topics most courses
don't cover. But you'll also build Node.js projects,
including working with real-life data and the SpaceX
API to build a NASA launch system.

Just want the cheatsheet? No problem! Please enjoy


and if you'd like to submit any suggestions, feel free to
email us at [email protected]

Contents

Running Node.js

Running Node.js

Node.js Global Object

Node.js Global Object

Node.js Module System

The require Function

Built-in Modules

Creating Modules

ECMAScript Modules

Node.js Packages
NPM Commands

package.json

node_modules

package-lock.json

Node.js Event Emitter

Node.js Event Emitter

Backend Concepts

Backend Concepts

Express.js

GET Routes

POST Routes

Routers

Node.js Folder Structure

Node.js Folder Structure

Cross Origin Resource Sharing

Cross Origin Resource Sharing

PM2 Commands

PM2 Commands

Useful Links

Useful Links

Running Node.js
For running Node.js:

Command Comments

node Run the Node REPL in your terminal

node —version Print your current Node version

node �lename.js Execute the Node code in �lename.js

� REPL stands for Read Eval Print Loop. This


is the list of steps that happen when you run
the node command and then type some code.

Node.js Global Object

In Node, we have a global object that we can


always access. Features that we expect to be
available everywhere live in this global object.

For example, to have some code execute after 5


seconds we can use either global.setTimeout
or just setTimeout . The global keyword is
optional.

setTimeout(() => {
console.log('hello');
}, 5000);

Probably the most famous global is


global.console.log which we write as just
console.log .

Node.js Module System

In Node.js, each �le is treated as a separate module.


In Node.js, each �le is treated as a separate module.
Modules provide us a way of re-using existing code.

The require Function


We can re-use existing code by using the Node built-
in require() function. This function imports code
from another module.

const fs = require('fs');
fs.readFileSync('hello.txt');

// OR...

const { readFileSync } = require('fs');


readFileSync('hello.txt');

Built-in Modules
Some modules like fs are built in to Node. These
modules contain Node-speci�c features.

Key built-in modules include:

• fs � read and write �les on your �le system

• path � combine paths regardless of which OS


you're using

• process � information about the currently running


process, e.g. process.argv for arguments passed
in or process.env for environment variables

• http � make requests and create HTTP servers

• https � work with secure HTTP servers using


SSL/TLS

• events � work with the EventEmitter

• crypto � cryptography tools like encryption and


hashing
Creating Modules
We can create our own modules by exporting a
function from a �le and importing it in another
module.

// In src/fileModule.js
function read(filename) { }
function write(filename, data) { }

module.exports = {
read,
write,
};

// In src/sayHello.js
const { write } = require('./fileModule.js'
write('hello.txt', 'Hello world!');

Some Node modules may instead use the shorthand


syntax to export functions.

// In src/fileModule.js
exports.read = function read(filename) { }
exports.write = function write(filename, data

ECMAScript Modules
The imports above use a syntax known as CommonJS
(CJS) modules. Node treats JavaScript code as
CommonJS modules by default. More recently, you
may have seen the ECMAScript module (ESM) syntax.
This is the syntax that is used by TypeScript.

// In src/fileModule.mjs
function read(filename) { }
function write(filename, data) { }
export {
read,
write,
};

// In src/sayHello.mjs
import { write } from './response.mjs';
write('hello.txt', 'Hello world!');

We tell Node to treat JavaScript code as an


ECMAScript module by using the .mjs �le extension.
Pick one approach and use it consistently throughout
your Node project.

Node.js Packages

Node developers often publicly share packages, that


other developers can use to help solve common
problems. A package is a collection of Node modules
along with a package.json �le describing the package.

To work with Node packages we use NPM. NPM


includes two things:

�. The NPM registry with a massive collection of


Node packages for us to use.

�. The NPM tool that you installed when you installed


Node.

� We can search the NPM registry for


packages at www.npmjs.com. The NPM tool will
by default install packages from this NPM
registry.

NPM Commands
Command Comments

Execute the current Node package de�ned by


npm start package.json
Defaults to executing node server.js

npm init Initialize a fresh package.json �le

Initialize a fresh package.json �le, accepting


npm init -y all default options.
Equivalent to npm init —yes

npm install Equivalent to npm i

Install a package from the NPM registry at


npm install
www.npmjs.com
<package>
Equivalent to npm i <package>

Install a package as a development


npm install -D dependency
<package> Equivalent to npm install —save-dev
<package>

npm install -g
Install a package globally.
<package>

npm update Update an already installed package


<package> Equivalent to npm up <package>

Uninstall a package from your node_modules/


npm uninstall
folder
<package>
Equivalent to npm un <package>

npm outdated Check for outdated package dependencies

Check for security vulnerabilities in package


npm audit
dependencies

Try to �x any security vulnerabilities by


npm audit �x
automatically updating vulnerable packages

package.json
Most Node applications we create include a
package.json �le, which means our Node applications
are also Node packages.

The package.json �le contains:

�. Name, version, description, license of the current


package.

�. Scripts to automate tasks like starting, testing,


and installing the current package.

�. Lists of dependencies that are required to be


installed by the current package.

node_modules
This folder lives next to your package.json �le.

When you run npm install the packages listed as


dependencies in your package.json are downloaded
from the NPM registry and put in the node_modules
folder.

It contains not just your direct dependencies, but also


the dependencies of those dependencies. The entire
dependency tree lives in node_modules.

package-lock.json
The package-lock.json �le is automatically created by
NPM to track the exact versions of packages that are
installed in your node_modules folder. Share your
package-lock.json with other developers on your
team to ensure that everyone is running the exact
same versions of every package in the dependency
tree.

Node.js Event Emitter

Node.js provides a built-in module to work with


events.

const EventEmitter = require('events');


require( );
const celebrity = new EventEmitter();

celebrity.on('success', () => {
console.log('Congratulations! You are the best!'
});

celebrity.emit('success'); // logs success message


celebrity.emit('success'); // logs success message again
celebrity.emit('failure'); // logs nothing

Many features of Node are modelled with the


EventEmitter class. Some examples include the
currently running Node process , a running HTTP
server, and web sockets. They all emit events that can
then be listened for using a listener function like
on() .

For example, we can listen for the exit event on the


current running process. In this case, the event has a
code associated with it to be more speci�c about how
the process is exiting.

const process = require('process');

process.on('exit', (code) => {


console.log(`About to exit with code: ${
});

Backend Concepts

Client-server architecture

Your frontend is usually the client. Your backend is


usually the server.

In a client-server architecture, clients get access to


data (or "resources") from the server. The client can
data (or "resources") from the server. The client can
then display and interact with this data.

The client and server communicate with each other


using the HTTP protocol.

API

Short for Application Programming Interface.

This is the set of functions or operations that your


backend server supports. The frontend interacts with
the backend by using only these operations.

On the web, backend APIs are commonly de�ned by a


list of URLs, corresponding HTTP methods, and any
queries and parameters.

CRUD

Short for Create Read Update and Delete.

These are the basic operations that every API


supports on collections of data. Your API will usually
save (or "persist") these collections of data in a
database.

RESTful

RESTful APIs are those that follow certain


constraints. These include:

• Client-server architecture. Clients get access to


resources from the server using the HTTP
protocol.

• Stateless communication. Each request contains


all the information required by the server to
handle that request. Every request is separate
from every other request.

• Cacheable. The stateless communication makes


caching easier.

In RESTful APIs each of our CRUD operations


corresponds to an HTTP method.

CRUD HTTP
Example
Operation method

POST /cards (save a


Create POST new card to the cards
collection)

GET /cards (get the


whole cards collection)
Read GET
or GET /cards/:cardId
(get an individual card)

PUT (or
PUT /cards/:cardId
more
Update (update an individual
rarely
card)
PATCH)

DELETE /cards/:cardId
(delete an individual
card) or more rarely
Delete DELETE
DELETE /cards (delete
the entire collection of
cards)

Express.js

GET Routes

// Get a whole collection of JSON objects


app.get("/cards", (req, res) =>
return res.json(cards);
});
});

// Get a specific item in a collection by ID


app.get("/cards/:cardId", (req
const cardId = req.params.cardId
return res.json(cards[cardId
});

POST Routes

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 verif


return res.json(card);
});

Routers

// In src/cards.router.js
const cardsRouter = express.Router

cardsRouter.get("/", (req, res


return res.json(cards);
});
cardsRouter.get("/:cardId", (req
const cardId = req.params.cardId
return res.json(cards[cardId
});

// In src/api.js
const cardsRouter = require('./cards.router'

const api = express.Router();

api.use('/cards', cardsRouter)

Node.js Folder Structure

One typical folder structure for an API following


RESTful architecture and using the Express
framework can be found below. Node servers
typically follow the Model View Controller pattern.
Models live together in one folder. Controllers are
grouped together based on which feature or
collection they are related to. Views are typically
managed by the front end, although some Node
servers may serve static HTML or use templating
engines like Handlebars.

node-project/
node_modules/
data/
database.json
src/
models/
comment.model.js
post.model.js
routes/
routes/
feeds/
feed.router.js
feed.controller.js
posts/
post.router.js
post.controller.js
api.js
services/
mongo.js
app.js
server.js
.gitignore
package-lock.json
package.json

This is just a reference. In the real world, every


project will have differences in the requirements
and the ideal project structure.

Cross Origin Resource


Sharing

Something all web developers soon come across is


Cross Origin Resource Sharing (CORS).

Browsers follow the Same Origin Policy (SOP),


which prevents requests being made across
different origins. This is designed to stop
malicious servers from stealing information that
doesn't belong to them.

Cross Origin Resource Sharing (CORS) allows us to


allow or whitelist other origins that we trust, so
that we can make requests to servers that don't
belong to us. For example, with CORS set up
properly, https://www.mydomain.com could make
a POST request to https://www.yourdomain.com.

In Express we commonly set up CORS using the


following middleware package:
https://www.npmjs.com/package/cors.

PM2 Commands

PM2 is a tool we use to create and manage Node.js


clusters. It allows us to create clusters of
processes, to manage those processes in
production, and to keep our applications running
forever. We can install the PM2 tool globally using
npm install -g pm2 .

Command Comments

List the status of all processes


pm2 list
managed by PM2.

pm2 start Start server.js in cluster mode


server.js -i 4 with 4 processes.

Start server.js in cluster mode


pm2 start with the maximum number of
server.js -i 0 processes to take full advantage
of your CPU.

pm2 logs Show logs from all processes.

pm2 logs Show older logs up to 200 lines


—lines 200 long.

Display a real-time dashboard in


pm2 monit your terminal with statistics for all
processes.

pm2 stop 0 Stop running process with ID 0.


pm2 restart
Restart process with ID 0.
0

pm2 delete Remove process with ID 0 from


0 PM2's list of managed processes.

pm2 delete Remove all processes from PM2's


all list.

Zero downtime reload of all


processes managed by PM2. For
pm2 reload
updating and reloading server
all
code already running in
production.

You might also like