Introduction to Node.js
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside a web browser. It allows developers to use JavaScript to write command-line tools and for server-side scripting—running scripts server-side to produce dynamic web page content before the page is sent to the user’s web browser.
Node.js was created by Ryan Dahl in 2009 and has since become one of the most popular backend technologies, powering companies like Netflix, PayPal, LinkedIn, and Uber.
Key Features
| Feature | Description |
|---|
| Asynchronous & Event-Driven | All APIs are non-blocking. The server never waits for an API to return data. |
| Single-Threaded | Uses event looping for high scalability without thread management overhead. |
| Fast Execution | Built on Chrome’s V8 engine, compiling JavaScript directly to machine code. |
| No Buffering | Outputs data in chunks, enabling efficient streaming. |
| Rich Ecosystem | Over 2 million packages available via NPM. |
| Cross-Platform | Runs on Windows, macOS, Linux, and more. |
When to Use Node.js
✅ Ideal for:
- Real-time applications (chat, gaming, collaboration tools)
- API servers and microservices
- Streaming applications
- Single Page Application (SPA) backends
- CLI tools and scripts
- IoT applications
❌ Not ideal for:
- CPU-intensive computations (video encoding, machine learning)
- Applications requiring multi-threading by design
- Monolithic enterprise applications with heavy business logic
The V8 Engine
At the core of Node.js is the V8 JavaScript engine, the same engine that powers Google Chrome. V8 compiles JavaScript directly to native machine code using Just-In-Time (JIT) compilation, resulting in exceptional performance.
How V8 Works
JavaScript Code → Parser → Abstract Syntax Tree (AST) → Interpreter (Ignition)
↓
Hot Code Optimization (TurboFan)
↓
Machine Code Execution
Key V8 Optimizations
- Hidden Classes: V8 creates hidden classes for objects to optimize property access
- Inline Caching: Remembers where to find object properties
- Garbage Collection: Automatic memory management with generational GC
Installation
To get started, you need to install Node.js on your machine.
Windows / macOS / Linux
- Visit the official Node.js website.
- Download the LTS (Long Term Support) version. This version is recommended for most users as it’s the most stable.
- Run the installer and follow the on-screen instructions.
Verifying Installation
Open your terminal or command prompt and run the following commands:
You should see the version numbers for both Node.js and npm (Node Package Manager).
The REPL (Read-Eval-Print Loop)
Node.js comes with a built-in REPL environment. It allows you to execute JavaScript code directly in the terminal.
To enter the REPL, simply type node in your terminal:
$ node
> console.log("Hello from Node.js!");
Hello from Node.js!
undefined
> 1 + 1
2
Press Ctrl + C twice to exit the REPL.
Your First Node.js Script
Let’s create a simple file to run with Node.js.
- Create a file named
app.js.
- Add the following code:
const message = "Hello, World!";
console.log(message);
const add = (a, b) => a + b;
console.log("2 + 3 =", add(2, 3));
- Run the file using the
node command:
Output:
Global Objects
In the browser, the global object is window. In Node.js, the global object is global.
console.log(global);
// Common globals
console.log(__dirname); // Path to current directory
console.log(__filename); // Path to current file
Note that DOM-related objects like document or window do not exist in Node.js.
The Event Loop
Understanding the Event Loop is crucial to mastering Node.js. It’s the mechanism that allows Node.js to perform non-blocking I/O operations despite JavaScript being single-threaded.
Event Loop Phases
┌───────────────────────────┐
┌─>│ timers │ ← setTimeout, setInterval
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
│ │ pending callbacks │ ← I/O callbacks deferred
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
│ │ idle, prepare │ ← internal use only
│ └─────────────┬─────────────┘ ┌───────────────┐
│ ┌─────────────┴─────────────┐ │ incoming │
│ │ poll │<─────┤ connections, │
│ └─────────────┬─────────────┘ │ data, etc. │
│ ┌─────────────┴─────────────┐ └───────────────┘
│ │ check │ ← setImmediate
│ └─────────────┬─────────────┘
│ ┌─────────────┴─────────────┐
└──┤ close callbacks │ ← socket.on('close')
└───────────────────────────┘
Example: Understanding Execution Order
console.log('1: Start');
setTimeout(() => {
console.log('2: Timeout callback');
}, 0);
setImmediate(() => {
console.log('3: Immediate callback');
});
process.nextTick(() => {
console.log('4: Next tick callback');
});
Promise.resolve().then(() => {
console.log('5: Promise resolved');
});
console.log('6: End');
// Output:
// 1: Start
// 6: End
// 4: Next tick callback
// 5: Promise resolved
// 2: Timeout callback (or 3, order varies)
// 3: Immediate callback (or 2)
process.nextTick() callbacks are processed before the event loop continues. Excessive use can starve I/O operations!
The Process Object
The process object is a global that provides information about, and control over, the current Node.js process.
Common Process Properties
// Environment variables
console.log(process.env.NODE_ENV); // 'development' or 'production'
console.log(process.env.PATH); // System PATH
// Process info
console.log(process.pid); // Process ID
console.log(process.ppid); // Parent process ID
console.log(process.version); // Node.js version
console.log(process.versions); // All dependency versions
console.log(process.platform); // 'darwin', 'win32', 'linux'
console.log(process.arch); // 'x64', 'arm64', etc.
// Command line arguments
console.log(process.argv); // Array of arguments
// node app.js --port=3000
// ['path/to/node', 'path/to/app.js', '--port=3000']
// Current working directory
console.log(process.cwd());
// Memory usage
console.log(process.memoryUsage());
// { rss: 30093312, heapTotal: 6537216, heapUsed: 4195024, external: 8272 }
Process Events
// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
console.error('Uncaught Exception:', err);
process.exit(1);
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM received. Shutting down gracefully...');
server.close(() => {
console.log('Process terminated');
process.exit(0);
});
});
// Before exit
process.on('beforeExit', (code) => {
console.log('Process beforeExit event with code:', code);
});
Advanced Setup Options
Using NVM (Node Version Manager)
Managing multiple Node.js versions is essential for professional development.
macOS/Linux:
# Install NVM
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash
# Install Node versions
nvm install 20 # Install Node 20
nvm install 18 # Install Node 18
nvm use 20 # Switch to Node 20
nvm alias default 20 # Set default version
nvm list # List installed versions
Windows (nvm-windows):
# Download from https://github.com/coreybutler/nvm-windows
nvm install 20.0.0
nvm use 20.0.0
Project Structure Best Practices
my-node-app/
├── src/
│ ├── config/ # Configuration files
│ ├── controllers/ # Route controllers
│ ├── middleware/ # Custom middleware
│ ├── models/ # Database models
│ ├── routes/ # Route definitions
│ ├── services/ # Business logic
│ ├── utils/ # Utility functions
│ └── app.js # Express app setup
├── tests/ # Test files
├── .env # Environment variables
├── .env.example # Environment template
├── .gitignore
├── package.json
└── README.md
Summary
- Node.js is a JavaScript runtime built on Chrome’s V8 engine
- The Event Loop enables non-blocking I/O with a single thread
- The
process object provides control over the Node.js process
- Use NVM to manage multiple Node.js versions
- Understand the Event Loop phases for better async code
- Follow consistent project structure patterns
Summary
In this chapter, we learned:
- What Node.js is and its key characteristics (Asynchronous, Single-threaded, V8 engine).
- How to install Node.js and verify the installation.
- How to use the REPL.
- How to write and run a simple Node.js script.
- The difference between the browser environment and Node.js (Global objects).