Node.js Fundamentals
Node.js runs JavaScript outside the browser. Built on V8 with an event-driven, non-blocking I/O model — excellent for scalable network applications and CLI tools.
// Node.js globals:
console.log(__dirname); // current directory
console.log(__filename); // current file path
console.log(process.env.NODE_ENV); // environment
console.log(process.argv); // CLI arguments
// Built-in modules:
const os = require("os");
const path = require("path");
const http = require("http");
console.log(process.version); // Node version
console.log(os.platform()); // "linux"/"win32"/"darwin"
console.log(os.cpus().length); // CPU count
console.log(os.freemem() / 1e9 + " GB free");
// Simple HTTP server:
const server = http.createServer((req, res) => {
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Hello from Node.js!</h1>");
} else if (req.url === "/api") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, timestamp: Date.now() }));
} else {
res.writeHead(404);
res.end("Not Found");
}
});
server.listen(3000, () => console.log("Server on :3000"));
⚡ Key Takeaways
- Node.js: JS on server — same language, no DOM
- Event-driven, non-blocking I/O — handles thousands of concurrent connections
- Built-in modules: http, fs, path, os, crypto, stream, etc.
- process object: env vars, CLI args, exit, platform info
- Raw http server is verbose — Express (next lesson) simplifies everything
🎯 Practice Exercises
EXERCISE 1
Build a Node HTTP server that serves: HTML at /, current time as JSON at /api/time, and a 404 page for everything else. Test with curl.