Node.js Tutorial
Build strong backend development skills from basics to production
Table of Contents
What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment that executes JavaScript code outside of a web browser. It allows developers to use JavaScript to write server-side code, build command-line tools, create desktop applications, and more.
Simple Definition: "Node.js is JavaScript on the server."
Official Definition: "Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine."
Key Characteristics
- Open-source - Free to use and modify
- Cross-platform - Runs on Windows, macOS, Linux
- Event-driven - Responds to events as they happen
- Non-blocking - Does not wait for operations to complete
- Asynchronous - Handles multiple tasks simultaneously
What Node.js is NOT
- Not a programming language
- Not a web framework (like Django or Rails)
- Not a web server (though you can create one)
What Node.js IS
- A runtime environment for JavaScript
- A way to run JS on servers
- A tool for building scalable network applications
How Node.js Works
Traditional Server Model (PHP, Ruby, Python)
Request 1 -> [Wait for DB query] -> Response
Request 2 -> [Wait... blocked] -> Response (slower)
Each request blocks the next one until completion.
Node.js Model
Request 1 -> [Start DB query] -> Continue to Request 2
Request 2 -> [Start DB query] -> Continue to Request 3
Request 1 -> [DB returns] -> Send Response
Multiple requests are handled simultaneously without blocking.
The Event Loop
Node.js uses a single thread with an event loop to handle multiple concurrent operations efficiently.
+---------------------------+
| JavaScript Code |
+-------------+-------------+
|
v
+---------------------------+
| Event Loop |
+-------------+-------------+
| Timers | I/O Callback|
+-------------+-------------+
| Idle/Prepare| Poll |
+-------------+-------------+
| Check | Close |
+-------------+-------------+
Key Features of Node.js
1) Asynchronous and Non-blocking I/O
const fs = require('fs');
fs.readFile('file.txt', (err, data) => {
console.log('File content:', data.toString());
});
console.log('This runs first!');
2) Event-Driven Architecture
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('userLogin', (user) => {
console.log(`${user} just logged in`);
});
myEmitter.emit('userLogin', 'John Doe');
3) Single-Threaded with Event Loop
Node.js uses a single thread with an event loop, making it lightweight and efficient.
4) Fast Code Execution
Built on Google's V8 engine, Node.js compiles JavaScript into machine code quickly.
5) NPM (Node Package Manager)
npm install express
npm install mongoose
npm install axios
6) Cross-Platform Support
Write once, run on Windows, macOS, and Linux.
7) No Buffering (Streaming)
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
const stream = fs.createReadStream('large-file.mp4');
stream.pipe(res);
}).listen(3000);
8) Scalability
const cluster = require('cluster');
const os = require('os');
if (cluster.isMaster) {
for (let i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
}
9) Real-time Capabilities
Great for chat apps, gaming, collaborative tools, and live streaming.
10) Large Ecosystem
- Express.js - Web framework
- Nest.js - Progressive Node.js framework
- Socket.io - Real-time communication
- Electron - Desktop applications
- React Native - Mobile applications
History of Node.js
- 2009: Ryan Dahl created Node.js; first release v0.1.0.
- 2010: npm created by Isaac Schlueter.
- 2011: Express.js released; Windows socket support improved.
- 2012: Joyent became primary sponsor.
- 2014: io.js fork created due to governance disagreements.
- 2015: Node.js Foundation formed; Node.js v4.0.0 and LTS model introduced.
- 2016-2019: Maturity, enterprise adoption, major ES and platform updates.
- 2020-2023: Node.js v14, v18, v20 with improved diagnostics, Fetch API, and test runner features.
Key Contributors & Roles
| Person/Group | Role | Contribution |
|---|---|---|
| Ryan Dahl | Creator | Designed and built original Node.js |
| Isaac Schlueter | npm Creator | Created npm and later led project |
| Joyent | Sponsor | Provided resources (2009-2015) |
| OpenJS Foundation | Steward | Manages Node.js development |
| Core Team | Maintainers | Community and company-backed maintenance |
Version History Summary
| Version | Release | Key Features |
|---|---|---|
| v0.1.0 | May 2009 | First release |
| v4.0.0 | Sep 2015 | First LTS after io.js merge |
| v6.0.0 | Apr 2016 | High ES6 support |
| v8.0.0 | May 2017 | Async/Await, N-API |
| v10.0.0 | Apr 2018 | HTTP/2, stable N-API |
| v12.0.0 | Apr 2019 | ES modules improvements |
| v14.0.0 | Apr 2020 | Diagnostic reporting |
| v16.0.0 | Apr 2021 | Apple Silicon support |
| v18.0.0 | Apr 2022 | Fetch API, Web Streams |
| v20.0.0 | Apr 2023 | Permission model, test runner improvements |
Node.js Architecture
+-------------------------------------+
| Node.js Application |
+-------------------------------------+
| JavaScript Code |
+-------------------------------------+
| Node.js API |
+-------------------------------------+
| Bindings (C++) |
+-------------------------------------+
| V8 Engine + Libuv |
+-------------------------------------+
Key Components
- V8 Engine - Executes JavaScript code
- Libuv - Handles asynchronous I/O operations
- Event Loop - Manages asynchronous callbacks
- Thread Pool - Handles blocking operations
- Bindings - Connects JavaScript with C++ libraries
Advantages & Disadvantages
Advantages
| Advantage | Description |
|---|---|
| High Performance | V8 compiles JS to machine code |
| Scalable | Handles many concurrent connections |
| Real-time Ready | Ideal for chat and collaboration |
| Large Ecosystem | Millions of npm packages |
| Full-stack JavaScript | Same language frontend + backend |
| Fast Development | Rapid prototyping and delivery |
Disadvantages
| Disadvantage | Description |
|---|---|
| CPU-intensive Tasks | Not ideal for heavy computation workloads |
| Callback Complexity | Nested callbacks can reduce readability |
| Tooling Gaps | Some tools are less mature than Java/.NET |
| API Changes | Frequent updates can impact compatibility |
| Dynamic Typing | JavaScript lacks strict type safety by default |
Who Uses Node.js?
Major Companies
| Company | Use Case |
|---|---|
| Netflix | Backend services and UI rendering |
| PayPal | Payment processing and dashboards |
| Mobile backend | |
| Uber | Matching and real-time updates |
| NASA | Data access layer |
| Walmart | Mobile app backend |
Popular Applications
- Trello - Project management platform
- Medium - Publishing platform
- GitHub Desktop - Built with Electron
- VS Code - Built with Electron
- Slack Desktop - Built with Electron
When to Use Node.js (vs When NOT to)
Use Node.js For
- REST APIs and microservices
- Real-time apps (chat, gaming)
- Single-page applications
- Streaming applications
- CLI tools and IoT apps
- Desktop apps via Electron
Avoid Node.js For
- Heavy CPU-bound processing
- Very large monolithic enterprise systems
- Strict type-safety requirements without TypeScript
Getting Started with Node.js
Installation
# Visit nodejs.org or use package manager
# On macOS (Homebrew)
brew install node
# On Ubuntu/Debian
sudo apt install nodejs npm
# Verify installation
node --version
npm --version
Your First Node.js Program
// app.js
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node.js!');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
node app.js
Summary
Node.js revolutionized server-side programming by bringing JavaScript to the backend with a non-blocking, event-driven architecture. From its beginnings in 2009 to becoming one of the most popular runtime environments today, Node.js has proven itself as a powerful tool for building fast, scalable network applications.
10 Interview Questions + 10 MCQs
Interview Pattern 10 Q&A.env, validate required keys at startup, avoid hard-coded secrets, and separate dev/stage/prod settings./api/v1, maintain backward compatibility, deprecate old endpoints with timeline, and document breaking changes clearly.10 Node.js Interview MCQs
Which status code is most appropriate for successful resource creation?
201 Created when a new resource is created.Best place to keep secret keys in Node.js app?
Which strategy best prevents callback hell in modern Node.js?
async/await improves readability and error handling.What should an Express error middleware include?
Which module is best for CPU-bound work inside Node process?
worker_threads is designed for CPU-heavy parallel tasks.