Master Node.js: From Basics to Production

Want to confidently build backend applications with Node.js? This pack is designed to take you from core fundamentals to real-world development skills. Inside, you’ll master how Node.js actually works — from the event loop and asynchronous programming to promises, streams, and error handling. No surface-level explanations — only practical knowledge you can apply in real projects. You’ll also explore the modern Node.js ecosystem: build APIs with Express, Fastify, and NestJS, work with databases using Prisma and Mongoose, and handle HTTP requests with tools like Axios and Got. Learn how to structure applications, manage modules (CommonJS vs ESM), and avoid common pitfalls like memory leaks. The pack includes essential developer tools and workflows: testing with Jest, Cypress, and Playwright, debugging techniques, logging, CLI development, and process management with PM2 and nodemon. Whether you’re preparing for a job interview, leveling up your backend skills, or building production-ready apps — this pack gives you structured, high-impact knowledge you can apply immediately. You may also be interested in: Node.js Stream Module Node.js Cluster Module Node.js Child Process Module Node.js Buffer API Interview Questions Node.js Crypto Module Node.js Operating System Module Node.js File System Module

Проверка знаний

Пройдите тест перед обучением, чтобы увидеть знакомые темы и найти пробелы.

Пройти тест

Уроки в мессенджере

Изучайте карточки и возвращайтесь к пройденному в интерактивных уроках.

Как проходят уроки

Интервальное повторение

Получайте отдельные карточки для повторения через интервалы, которые помогают дольше помнить материал.

Как работает повторение
Node.js Introduction

Node.js is an open source, cross-platform runtime environment and library that is used for running web applications outside the client’s browser.

1/113
What is Node.js

Node.js is an open-source and cross-platform JavaScript runtime environment.


It is a popular tool for almost any kind of project! Node.js runs the V8 JavaScript engine, Google Chrome’s core, outside the browser.

2/113
Why Node.js

Node.js is a cross-platform runtime, perfect for a wide range of use cases.


Its huge community makes it easy to get started. It uses the V8 engine to compile JavaScript and runs at lightning-fast speeds.

3/113
History of Node.js

Node.js was written initially by Ryan Dahl in 2009, about thirteen years after the introduction of the first server-side JavaScript environment, Netscape’s LiveWire Pro Web.

4/113
Nodejs vs Browser

Both the browser and Node.js use JavaScript as their programming language.


Building apps that run in the browser is entirely different than building a Node.js application. Even though it’s always JavaScript, some key differences make the experience radically different.

5/113
Running Node.js Code

The usual way to run a Node.js program is to run the globally available node command (once you install Node.js) and pass the name of the file you want to execute.

6/113
Node.js Modules

We split our code into different files to maintain, organize and reuse code whenever possible.


A module system allows us to split and include code and import code written by other developers whenever required.

7/113
CommonJS vs ESM

Node.js supports two module systems. CommonJS uses require() to load modules and module.exports to expose values. ECMAScript modules (ESM) use import and export.

Use a .cjs file for CommonJS and a .mjs file for ESM. A .js file is interpreted according to package configuration and Node.js module detection rules, so neither system is universally the default. Choose a module format for a project and check how its dependencies are exported before importing them.

8/113
ESM

ESM (ECMAScript Modules) is a standardized module system in JavaScript that allows for the organized, maintainable, and reusable structuring of code.

9/113
Custom Modules

Modules are the collection of JavaScript codes in a separate logical file that can be used in external applications based on their related functionality.


There are two ways to create modules in Node.js i.e. either via CommonJS or ESM.

10/113
global keyword

In browsers, the top-level scope is the global scope, and its global object is called the window object.


Within the browser, var something will define a new global variable inside the window object.


In Node.js, this is different.

11/113
npm

npm is the standard package manager for Node.js.

12/113
Global Install vs Local Install

NodeJS and NPM allow two methods of installing dependencies/packages: Local and Global.


This is mainly used when adding a package or dependency as part of a specific project you’re working on.

13/113
Local Installation

Locally installed packages are available only to the project where the packages are installed, while the globally installed packages can be used any where without installing them into a project.


Another use case of the global packages is when using CLI tools.

14/113
Updating Packages

npm provides various features to help install and maintain the project’s dependencies.


Dependencies get updates with new features and fixes, so upgrading to a newer version is recommended. We use npm update commands for this.

15/113
Running Scripts

In Node.js, npm scripts are used for the purpose of initiating a server, starting the build of a project, and also for running the tests. We can define this scripts in the package.json file of the folder. Also, we can split the huge scripts into many smaller parts if it is needed.

16/113
npm workspaces

Workspace is a generic term that refers to the set of npm CLI features that support managing multiple packages from your local file system from within a singular top-level root package.

17/113
Creating Packages

npm packages allow you to bundle some specific functionality into a reusable package which can then be uploaded to some package registry such as npm or GitHub packages and then be installed and reused in projects using npm.

18/113
Semantic Versioning

Semantic Versioning is a standard for versioning software that’s widely adopted in the npm ecosystem.


It provides a clear and consistent way to communicate changes in a software package to users.

19/113
Error Handling

Handle a failure where its result is received. Synchronous operations can throw and be caught with try/catch; callback APIs often pass an error first; promises reject and can be handled with .catch() or try/catch around await. Event emitters may require an error listener.

Separate expected operational failures, such as a missing file, from programming defects. For expected cases, inspect an error code and provide a useful response. For unexpected cases, preserve the error details for diagnosis rather than silently ignoring the failure.

20/113
Javascript Errors

JavaScript uses Error objects to describe failures. Common built-in subclasses include TypeError for an invalid type, RangeError for a value outside an allowed range, ReferenceError for an unresolved name, and SyntaxError for invalid syntax. Other error classes, such as AggregateError, also exist.

In Node.js, system operations can produce errors with codes such as ENOENT. Read the error name, message, and code when present; do not assume a fixed exhaustive list of error types.

21/113
System Errors

Node.js surfaces many operating-system failures as system errors. Inspect error.code to distinguish common cases: ENOENT means a path does not exist, EACCES means access was denied, EADDRINUSE means an address is already in use, and ECONNRESET means a connection was reset by its peer.

EMFILE means this process has too many open file descriptors; ENFILE refers to a system-wide open-file limit. Handle an expected code close to the operation that produced it and preserve the original error for unexpected failures.

22/113
User Specified Errors

User specified errors can be created by extending the base Error object, a built-in error class.


When creating errors in this manner, you should pass a message string that describes the error.

23/113
Assertion Errors

An AssertionError in Node.js is an error that is thrown when the assert module determines that a given expression is not truthy.


The assert module is a built-in Node.js module that provides a simple set of assertion tests that can be used to test the behavior of your code.

24/113
Uncaught Exceptions

When a JavaScript error is not properly handled, an uncaughtException is emitted.


These suggest the programmer has made an error, and they should be treated with the utmost priority.

25/113
Async errors

Asynchronous APIs report errors in different ways. A callback-style API often passes an error as its first callback argument. A promise-based API rejects; handle it with .catch() or with try/catch around an awaited promise. An EventEmitter may emit an error event that needs a listener.

A try/catch around the call that starts asynchronous work does not catch an error thrown later in a separate callback. Handle the error at the point where the asynchronous result is received.

26/113
Stack Trace

The stack trace is used to trace the active stack frames at a particular instance during the execution of a program.


The stack trace is useful while debugging code as it shows the exact point that has caused an error.

27/113
Using Debugger

Node.js includes a command-line debugging utility.


The Node.js debugger client is not a full-featured debugger, but simple stepping and inspection are possible.

28/113
npx

npx runs a command from a package. It uses npm exec behavior: npm first looks for a matching local dependency and may download a missing package into the npm cache for the command. This avoids a permanent global installation, but it does not mean no package files are installed at all.

Use it for a one-time tool invocation, such as npx create-vite. Review the package and version before running code from a registry. The old standalone npx package is deprecated; npx is distributed with modern npm.

29/113
Nodejs async programming

Asynchronous programming lets a Node.js process start an I/O operation and continue other work while the result is pending. Completion is reported later through a callback, promise, or event. This can improve throughput for I/O-heavy services, but it does not make every operation parallel or remove all ordering.

Within one JavaScript thread, callbacks run on the event loop. CPU-intensive JavaScript can still block it. Use await when one step depends on a previous promise, and handle rejections so failures are not lost.

30/113
Promises

A promise is commonly defined as a proxy for a value that will eventually become available.


Asynchronous functions use promise behind the scenes, so understanding how promises work is fundamental to understanding how “async” and “await” works.

31/113
Async/Await

Async/Await is a special syntax to work with promises in a more comfortable fashion.


It’s easy to understand and use.

32/113
Callbacks

Node.js, being an asynchronous platform, doesn’t wait around for things like file I/O to finish - Node.js uses callbacks.


A callback is a function called at the completion of a given task; this prevents any blocking, and allows other code to be run in the meantime.

33/113
setTimeout

The setTimeout runs a function after the specified period expires.


Times are declared in milliseconds.

34/113
setInterval

setInterval(callback, delay) schedules repeated callback execution with a delay measured in milliseconds. The timing is approximate: a busy event loop can postpone a callback. It returns a timer object that can be passed to clearInterval() to stop further calls.

Unlike setTimeout(), it schedules repeated calls while active. Clear it when the repeated task is no longer needed; an active timer can keep a Node.js process running.

35/113
setImmediate

setImmediate(callback) schedules a callback for the event loop’s check phase, after the current poll phase. It runs once and returns an Immediate object that can be cancelled with clearImmediate().

It differs from setTimeout(callback, 0), which uses timer scheduling. Their relative order can vary when scheduled from top-level code; do not rely on one always running first.

36/113
process.nextTick()

Every time the event loop takes a full trip, we call it a tick.


When we pass a function to process.nextTick(), we instruct the engine to invoke this function at the end of the current operation before the next event loop tick starts.

37/113
Event Emitter

In Node.js, an event can be described simply as a string with a corresponding callback.


An event can be “emitted” (or, in other words, the corresponding callback be called) multiple times or you can choose to only listen for the first time it is emitted.

38/113
Event Loop

The Event Loop is one of the most critical aspects of Node.js. Why is this so important? Because it explains how Node.js can be asynchronous and have non-blocking I/O, it explains the “killer feature” of Node.js, which made it this successful.

39/113
Working with Files

You can programmatically manipulate files in Node.js with the built-in fs module. The name is short for “file system,” and the module contains all the functions you need to read, write, and delete files on the local machine.

40/113
process.cwd()

The process.cwd() method returns the current working directory of the Node.js process.

41/113
path module

The path module provides utilities for working with file and directory paths. It’s built-in to Node.js core and can simply be used by requiring it.

42/113
fs module

File System or fs module is a built in module in Node that enables interacting with the file system using JavaScript. All file system operations have synchronous, callback, and promise-based forms, and are accessible using both CommonJS syntax and ES6 Modules.

43/113
__dirname

The __dirname in a node script returns the path of the folder where the current JavaScript file resides. __filename and __dirname are used to get the filename and directory name of the currently executing file.

44/113
__filename

The __filename in Node.js returns the filename of the executed code. It gives the absolute path of the code file. The following approach covers implementing __filename in the Node.js project.

45/113
Glob

The glob pattern is most commonly used to specify filenames, called wildcard characters, and strings, called wildcard matching.

46/113
Globby

User-friendly glob matching Based on fast-glob but adds a bunch of useful features.

47/113
fs-extra

fs-extra adds file system methods that aren’t included in the native fs module and adds promise support to the fs methods. It also uses graceful-fs to prevent EMFILE errors. It should be a drop in replacement for fs.

48/113
Chokidar

Chokidar is a fast open-source file watcher for node. js. You give it a bunch of files, it watches them for changes and notifies you every time an old file is edited; or a new file is created.

49/113
Command Line Applications

Command Line Applications are applications that can be run from the command line. They are also called CLI (Command Line Interface) applications. Users can interact with clients entirely by terminal commands. They are very useful for automation and building tools.

50/113
dotenv

dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.

51/113
process.env

In Node. js, process. env is a global variable that is injected during runtime. It is a view of the state of the system environment variables. When we set an environment variable, it is loaded into process.env during runtime and can later be accessed.

52/113
Exiting and exit codes

Exiting is a way of terminating a Node.js process by using node.js process module.

53/113
Process stdin

The process.stdin is a standard Readable stream which listens for user input and is accessible via the process module. It uses on() function to listen for input events.

54/113
Prompts

Prompts is a higher level and user friendly interface built on top of Node.js’s inbuilt Readline module. It supports different type of prompts such as text, password, autocomplete, date, etc. It is an interactive module and comes with inbuilt validation support.

55/113
Inquirer

Inquirer.js is a collection of common interactive command line interfaces for taking inputs from user.


It is promise based and supports chaining series of prompt questions together, receiving text input, checkboxes, lists of choices and much more.

56/113
Process stdout

The process.stdout property is an inbuilt application programming interface of the process module which is used to send data out of our program. A Writable Stream to stdout. It implements a write() method. console.log() prints to the process.stdout.write() with formatted output or new line.

57/113
Chalk

Chalk is a clean and focused library used to do string styling in your terminal applications. With it, you can print different styled messages to your console such as changing font colors, font boldness, font opacity, and the background of any message printed on your console.

58/113
Figlet

This package aims to fully implement the FIGfont spec in JavaScript, which represents the graphical arrangement of characters representing larger characters. It works in the browser and with Node.js.

59/113
Cli progress

CLI-Progress is a package that provides a custom progress bar for CLI applications.

60/113
process.argv

process.argv is an array of parameters that are sent when you run a Node.js file or Node.js process.

61/113
Commander.js

Commander is a light-weight, expressive, and powerful command-line framework for node.js. with Commander.js you can create your own command-line interface (CLI).

62/113
APIs

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other.

63/113
Express.js

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multi-page, and hybrid web application.

64/113
Fastify

Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture, inspired by Hapi and Express.

65/113
NestJS
NestJS is a progressive Node.js framework for creating efficient and scalable server-side applications. Visit the following resources to learn more:

NestJS organizes server-side applications into modules. Controllers receive requests, while providers hold reusable logic and can be injected as dependencies. This structure helps separate routing from business behavior. A small service may need little framework setup; choose modules and providers when the application benefits from explicit organization.

66/113
Hono
Hono is a lightweight, simple, and fast web framework for Cloudflare Workers, Deno, Bun, and other applications. It is a modern web application that is both fast and flexible. It offers inbuilt support for TypeScript, and easy development in a local environment. Using Hono, It is easy to create publishable web applications with Deno, Bun, and Cloudflare Workers. Visit the following resources to learn more:
67/113
Making API calls with HTTP
You can make API calls using the http module in Node.js as well. Here are the two methods that you can use: http.get() - Make http GET requests. http.request() - Similar to http.get() but enables sending other types of http requests (GET requests inclusive). Visit the following resources to learn more:
68/113
Axios
Axios is a promise-based HTTP Client for node.js and the browser. Used for making requests to web servers. On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests. Visit the following resources to learn more:
69/113
Ky

Ky is a small HTTP client built on the Fetch API. It supports modern browsers and current Node.js versions with native Fetch, as well as other JavaScript runtimes. It provides a compact API for requests and JSON responses.

Compared with plain fetch(), Ky offers method shortcuts, retry behavior, timeouts, and configurable defaults. Check the installed Ky version’s runtime requirements before using it in a Node.js project.

70/113
fetch
The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise. Visit the following resources to learn more:
71/113
Got
Got is a lighter, human-friendly, and powerful HTTP request library explicitly designed to work with Node.js. It supports pagination, RFC compliant caching, makes an API request again if it fails, supports cookies out of the box, etc. Visit the following resources to learn more:
72/113
JSON Web Token
JWT, or JSON-Web-Token, is an open standard for sharing security information between two parties — a client and a server. Each JWT contains encoded JSON objects, including a set of claims. JWTs are signed using a cryptographic algorithm to ensure that the claims cannot be altered after the token is issued. Visit the following resources to learn more:
73/113
Passport js
Passport.js is authentication middleware for Node.js. It makes implementing authentication in express apps really easy and fast. It is extremely flexible and modular. It uses “strategies” to support authentication using a username and password, Facebook, Twitter, and a lot of other sites. Visit the following resources to learn more:
74/113
Keep App Running

During development, a file watcher such as node --watch app.js or nodemon can restart an application when its source changes. This shortens the edit-and-test cycle, but a watch flag does not by itself supervise a production service.

For production, use a process manager or hosting platform with restart policies, logs, health checks, and controlled deployment. Investigate repeated crashes instead of relying on automatic restarts alone.

75/113
Node.js --watch

Run node --watch app.js to start Node.js in watch mode. When the entry file or a required or imported module changes, Node.js restarts the process. This is useful during development, where it shortens the edit-and-restart cycle.

Watch mode requires a script path. It does not preserve in-memory state across restarts, and it is not a substitute for a production process manager. Use --watch-path only when you need to select particular watched paths; platform support for that option differs.

76/113
Nodemon
In Node.js, you need to restart the process to make changes take effect. This adds an extra step to your workflow. You can eliminate this extra step by using nodemon or PM2 to restart the process automatically. nodemon is a command-line interface (CLI) utility developed by @rem that wraps your Node app, watches the file system, and automatically restarts the process. Visit the following resources to learn more:
77/113
Template Engines
Template engine helps us to create an HTML template with minimal code. Also, it can inject data into HTML template at client side and produce the final HTML. Some examples of template engines in Node.js are: Nunjucks Jade Vash EJS Handlebars HAML
78/113
EJS
EJS is a template language or engine that allows you to generate HTML markup with pure JavaScript. And this is what makes it perfect for Nodejs applications. In simple words, the EJS template engine helps to easily embed JavaScript into your HTML template. Visit the following resources to learn more:
79/113
Pug
Pug is a JavaScript template engine. It is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers. Pug was formerly called Jade. Pug is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers Visit the following resources to learn more:
80/113
Marko
Marko is a fast and lightweight HTML-based templating engine that compiles templates to CommonJS modules and supports streaming, async rendering, and custom tags. It is HTML re-imagined as a language for building dynamic and reactive user interfaces. Visit the following resources to learn more:
81/113
What is Database
A database is an organized collection of structured information, or data, typically stored electronically in a computer system. A database is usually controlled by a database management system (DBMS). Visit the following resources to learn more:
82/113
Mongoose
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. Mongoose provides a straight-forward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks and more, out of the box. Visit the following resources to learn more:
83/113
Prisma
Prisma provides an open source next-generation ORM in the TypeScript ecosystem. It offers a dedicated API for relation filters. It provides an abstraction layer that makes you more productive compared to writing SQL. Prisma currently supports PostgreSQL, MySQL, SQL Server, SQLite, MongoDB and CockroachDB. Visit the following resources to learn more:
84/113
Native Drivers
Another way to connect to different databases in Node.js is to use the official native drivers provided by the database. For example, here is the list of drivers by MongoDB
85/113
Knex
Knex.js is a “batteries included” SQL query builder for PostgreSQL, CockroachDB, MSSQL, MySQL, MariaDB, SQLite3, Better-SQLite3, Oracle, and Amazon Redshift designed to be flexible, portable, and fun to use. Visit the following resources to learn more:
86/113
Drizzle
Drizzle lets you build your project the way you want, without interfering with your project or structure. Using Drizzle you can define and manage database schemas in TypeScript, access your data in a SQL-like or relational way, and take advantage of opt-in tools to make your developer experience amazing. Visit the following resources to learn more:
87/113
TypeORM
TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8). Its goal is to always support the latest JavaScript features and provide additional features that help you to develop any kind of application that uses databases - from small applications with a few tables to large scale enterprise applications with multiple databases. TypeORM supports both Active Record and Data Mapper patterns, unlike all other JavaScript ORMs currently in existence, which means you can write high quality, loosely coupled, scalable, maintainable applications the most productive way. Visit the following resources to learn more:
88/113
Sequelize
Sequelize is an easy-to-use and promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, DB2, Microsoft SQL Server, and Snowflake. It features solid transaction support, relations, eager and lazy loading, read replication and more. An ORM is known as Object Relational Mapper. This is a tool or a level of abstraction which maps(converts) data in a relational database into programmatic objects that can be manipulated by a programmer using a programming language(usually an OOP language). ORMs solely exist to map the details between two data sources which due to a mismatch cannot coexist together. Visit the following resources to learn more:
89/113
Prisma
Prisma is an ORM that helps app developers build faster and make fewer errors. Combined with its Data Platform developers gain reliability and visibility when working with databases. Visit the following resources to learn more:
90/113
Native drivers

A native database driver lets a Node.js application connect directly to a particular database without an ORM abstraction. For example, the official MongoDB Node.js driver connects to MongoDB and exposes operations on databases and collections. SQL databases have their own driver packages and APIs.

Choose a driver that matches the database and supported Node.js version. Open a connection or pool, run queries or commands, handle errors, and close resources when the application shuts down. A driver gives direct control over database operations; an ORM adds a higher-level mapping layer.

91/113
Testing
Software testing is the process of verifying that what we create is doing exactly what we expect it to do. The tests are created to prevent bugs and improve code quality. The two most common testing approaches are unit testing and end-to-end testing. In the first, we examine small snippets of code, in the second, we test an entire user flow. Visit the following resources to learn more:
92/113
Vitest
Vitest is a Vite-native unit testing framework that’s Jest-compatible. Vitest is a powerful testing library built on top of Vite that is growing in popularity. You can use Vitest for a range of testing needs, such as unit, integration, end-to-end (E2E), snapshot, and performance testing of functions and components. ESM, TypeScript, JSX. Out-of-box ESM, TypeScript and JSX support powered by esbuild. Vitest is free and open source. Visit the following resources to learn more:
93/113
node:test
node:test is a built-in module in Node.js that provides a simple, asynchronous test runner. It’s designed to make writing tests as straightforward as writing any other code. Simplicity: Easy to use and understand. Asynchronous Support: Handles asynchronous code gracefully. Subtests: Allows for organizing tests into hierarchical structures. Hooks: Provides beforeEach and afterEach hooks for setup and teardown. Visit the following resources to learn more:
94/113
Jest
Jest is a delightful JavaScript Testing Framework with a focus on simplicity. It works with projects using: Babel, TypeScript, Node, React, Angular, Vue and more! Visit the following resources to learn more:
95/113
Playwright
Playwright is an open-source automation library developed by Microsoft for testing and automating web applications. 1 It offers a unified API to control Chromium, Firefox, and WebKit browsers, making it a versatile choice for cross-browser testing. Playwright provides a high-level API to interact with web pages. You can write scripts to simulate user actions, such as clicking buttons, filling forms, and navigating through different pages. Playwright handles the underlying browser interactions, making it easy to write and maintain tests. Visit the following resources to learn more:
96/113
Cypress
Cypress is a new front end testing tool built for the modern web. It enables you to write faster, easier and more reliable tests. Visit the following resources to learn more:
97/113
Node.js Logging
Logging is an essential part of understanding the complete application life cycle of the Node.js application. We can much more easily and quickly fix errors by looking at logs throughout the development process, from creating to debugging to designing new features. Error, warn, info, and debug are the four basic logging levels in Node.js. Logging involves persistently collecting information about an application’s runtime behaviour. Visit the following resources to learn more:
98/113
Winston
winston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file. Visit the following resources to learn more:
99/113
Morgan
Morgan is a NodeJS and express.js middleware to log the HTTP request and error, simplifying the debugging process. It provides flexibility in defining the format of log messages and helps override the output destination for your logs. Visit the following resources to learn more:
100/113
Keep your app running in Production
PM2 lets you run your nodejs scripts forever. In the event that your application crashes, PM2 will also restart it for you. Visit the following resources to learn more:

A production process manager such as PM2 can restart a Node.js application after a crash and keep it running in the background. Configure startup behavior, logs, and health checks so an operator can see whether the app is actually serving requests. A restart policy helps availability but does not fix the underlying crash; inspect logs and address repeated failures.

101/113
Pm2
PM2 is a production process manager for Node.js applications with a built-in load balancer. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks. Visit the following resources to learn more:
102/113
Nodejs Threads

JavaScript callbacks in a typical Node.js process run on one main event-loop thread. The runtime can perform asynchronous I/O and use an internal worker pool, so the entire application is not limited to one operating-system thread.

For CPU-heavy JavaScript, node:worker_threads can run code on additional threads. Child processes provide separate process isolation. Choose the model based on the task and measure the overhead of creating and communicating with workers.

103/113
Child Process

node:child_process starts separate operating-system processes. spawn() streams input and output, exec() runs a command in a shell and buffers output, and execFile() launches an executable directly by default. fork() starts another Node.js process with an IPC channel.

Not every child process has IPC; configure it when needed. Choose the method according to shell use, output size, and communication needs. Treat untrusted input carefully when a shell is involved.

104/113
Cluster

node:cluster creates multiple Node.js worker processes that can share a server port and handle incoming connections. Each worker is a separate process with its own memory and event loop. The primary process can fork workers and observe their lifecycle.

Cluster can use multiple CPU cores for a server workload, while worker_threads runs multiple JavaScript threads within one process. Process separation changes memory and communication costs; it does not automatically make every request faster.

105/113
Worker Threads

node:worker_threads runs JavaScript on additional threads within one Node.js process. Workers are useful for CPU-intensive JavaScript and exchange messages through ports. They can also share selected memory with SharedArrayBuffer, which requires careful synchronization.

A worker has its own JavaScript execution context. Creating workers does not automatically prevent races, deadlocks, or excessive resource use. For ordinary asynchronous I/O, a new worker is often unnecessary.

106/113
Nodejs streams
Streams are a type of data handling methods and are used to read, write or transform chunks of data piece by piece without keeping it in memory all at once. There are four types of streams in Node.js. Readable: streams from which data can be read. Writable: streams to which we can write data. Duplex: streams that are both Readable and Writable. Transform: streams that can modify or transform the data as it is written and read. Multiple streams can be chained together using pipe() method. Visit the following resources to learn more:
107/113
More Debugging
Debugging is a concept to identify and remove errors from software applications. Here, we will learn about the technique to debug a Node.js application. Using console.log to debug the code generally dives into an infinite loop of “stopping the app and adding a console.log, and start the app again” operations. Besides slowing down the development of the app, it also makes the writing dirty and creates unnecessary code. Finally, trying to log out variables alongside with the noise of other potential logging operations, may make the process of debugging difficult when attempting to find the values you are debugging. Visit the following resources to learn more:
108/113
Memory Leaks

A memory leak occurs when an application keeps retaining data it no longer needs. Objects that remain reachable through caches, event listeners, timers, or global references cannot be reclaimed by garbage collection. Memory use may grow over time and eventually slow or crash the process.

Compare heap snapshots or memory measurements under a repeatable workload, find the references retaining unwanted objects, and release or bound them. Rising memory alone is not proof of a leak: caches, buffers, and normal workload changes also affect usage.

109/113
Node Inspect
Node.js provides a built-in DevTools-based debugger to allow debugging Node.js applications. Visit the following resources to learn more:

The built-in Node.js inspector supports breakpoints, stepping, and examining values while code runs. Start a script with node inspect app.js for a command-line debugging session, or use --inspect to connect a compatible DevTools client. Keep the inspector endpoint private because a connected debugger can control the process.

110/113
Using APM
As much fun as it is to intercept your container requests with inspect and step through your code, you won’t have this option in production. This is why it makes a lot of sense to try and debug your application locally in the same way as you would in production. In production, one of your tools would be to login to your remote server to view the console logs, just as you would on local. But this can be a tedious approach. Luckily, there are tools out there that perform what is called log aggregation, such as Stackify. These tools send your logs from your running application into a single location. They often come with high-powered search and query utilities so that you can easily parse your logs and visualize them. Visit the following resources to learn more:
111/113
Garbage Collection
Memory management in JavaScript is performed automatically and invisibly to us. We create primitives, objects, functions… All that takes memory. The main concept of memory management in JavaScript is reachability. Visit the following resources to learn more:
112/113
Nodejs core modules
These are the core modules that come with Node.js out of the box. This module provides tools or APIs for performing out certain standard Node.js operations. like interacting with the file system, url parsing, or logging information to the console. Learn more from the following resources:
113/113