Node.js is a JavaScript runtime built on Chrome's V8 engine. It is designed for fast, non-blocking server-side applications.
- Node.js uses a single-threaded event loop to manage asynchronous work.
- The event loop lets Node handle many operations without blocking the main thread.
- I/O tasks are usually delegated to the system or libuv, then callbacks are queued when ready.
- timers
- pending callbacks
- idle, prepare
- poll
- check
- close callbacks
- Synchronous code runs first.
- Microtasks and promise callbacks are handled with high priority.
setTimeoutandsetImmediatedo not always run in the same order.- CPU-heavy work can block the event loop and slow the app.
- A Buffer is a raw binary data container.
- Buffers are useful for files, streams, network packets, and binary APIs.
const buf = Buffer.from("hello");
console.log(buf.toString());Streams let you process data piece by piece instead of loading everything into memory at once.
- readable
- writable
- duplex
- transform
- memory efficient
- good for large files
- useful for request/response piping
const fs = require("fs");
const readStream = fs.createReadStream("big-file.txt");
readStream.on("data", chunk => {
console.log(chunk.toString());
});fsgives file-system access.- It supports synchronous and asynchronous methods.
readFilewriteFileappendFileunlinkmkdirreaddirstat
const fs = require("fs");
fs.readFile("notes.txt", "utf8", (err, data) => {
if (err) throw err;
console.log(data);
});const data = fs.readFileSync("notes.txt", "utf8");- npm is Node's package manager.
- It installs and manages third-party dependencies.
package.json: project metadata and scriptspackage-lock.json: exact dependency tree
npm initnpm installnpm install <package>npm install -D <package>npm uninstall <package>npm run <script>
dotenvloads environment variables from a.envfile intoprocess.env.- This keeps secrets out of source code.
require("dotenv").config();
console.log(process.env.PORT);- Store secrets in
.env - Add
.envto.gitignore - Use environment variables for ports, keys, and database URLs
Node supports modular code organization.
const fs = require("fs");
module.exports = myValue;import fs from "fs";
export default myValue;- CommonJS is traditional in Node.
- ES Modules are the modern standard.
- Use one module system consistently within a project.
Express is a web framework for Node.js that simplifies routing, middleware, and request handling.
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Server running on port 3000");
});- Routes map HTTP methods and paths to handlers.
- Common methods:
GET,POST,PUT,PATCH,DELETE
app.get("/users", (req, res) => {
res.send("All users");
});
app.post("/users", (req, res) => {
res.send("Create user");
});Middleware is a function that runs between request and response.
- read or modify
reqandres - end the response
- call
next()to continue - handle errors
- application-level middleware
- router-level middleware
- built-in middleware
- third-party middleware
- error-handling middleware
app.use((req, res, next) => {
console.log(req.method, req.url);
next();
});express.json()express.urlencoded({ extended: true })express.static()
app.get("/users/:id", (req, res) => {
res.send(req.params.id);
});app.get("/search", (req, res) => {
res.send(req.query.term);
});- Cookies are small pieces of data stored in the browser.
- Sessions store server-side state and usually use a cookie as the session identifier.
- auth tokens
- preferences
- tracking identifiers
- logged-in state
- temporary user data
- server-managed carts
Express uses special error middleware.
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ message: "Something went wrong" });
});- validate input early
- return proper status codes
- keep errors consistent
- avoid leaking sensitive stack traces in production
- order of middleware matters
next()is required to continue- route handlers can be arrays or separate functions
res.status(...).json(...)is a common response pattern