Node.js Basics
JavaScript on the server
Node.js runs JavaScript outside the browser, using Chrome's V8 engine. With it you can build APIs, command-line tools and real-time servers, all in the same language as your front end.
What's different from the browser
| Browser | Node.js |
|---|---|
window, document, the DOM | no DOM |
| limited file access | full file system (fs) |
| fetch, localStorage | fetch, plus http, fs, path, process… |
| runs your user's code | runs your server code |
Non-blocking I/O
Node handles many connections on a single thread by not waiting: while one request waits for the database, it serves others. That makes it great for I/O-heavy apps like APIs and chat. CPU-heavy work (video encoding, big maths) blocks the thread, so move it to worker threads or another service.
Built-in modules
import fs from "node:fs/promises";
import path from "node:path";
const text = await fs.readFile(path.join("data", "notes.txt"), "utf8");
Running code
node app.jsruns a file.node --watch app.jsrestarts automatically on changes (Node 18+).process.env.PORTreads environment variables.
💡 Install the LTS (long-term support) version of Node.js from nodejs.org.
Example
// server.js — a tiny HTTP server with only built-in modules
import http from "node:http";
const server = http.createServer((req, res) => {
if (req.url === "/api/hello") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ message: "Hello from Node!" }));
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
});
const PORT = process.env.PORT ?? 3000;
server.listen(PORT, () => console.log(`Running on http://localhost:${PORT}`));
// Run: node server.js (package.json needs "type": "module")
// 💻 Run on a computer with Node.js