From Here to Where?
The Path Module
Section titled “The Path Module”We need to construct the path to our file. We could try to smash strings together like __dirname + '/pages/index.html', but that’s reckless driving. Windows uses backslashes \, Mac/Linux use forward slashes /. String concatenation often results in broken paths.
We use the core path module to handle this chaos.
Fig 1: GPS Navigation. Calculating the optimal route.
The Navigator vs The Driver
Section titled “The Navigator vs The Driver”Important distinction:
pathmodule (The Navigator): It purely calculates strings. It doesn’t know if the file actually exists. It just tells you “The address would be here.”fsmodule (The Driver): Actually goes to the disk to read/write files. Usepathto tellfswhere to go.
const path = require("path");
app.get("/", (req, res) => { // __dirname = The directory where THIS script lives // We join it with the relative path to the file const fullPath = path.join(__dirname, "pages", "index.html");
res.sendFile(fullPath);});U-Turns and Detours (..)
Section titled “U-Turns and Detours (..)”path.join() is smarter than simple string concatenation. It understands that .. means “Go up one level”.
This is crucial because typically your server.js is in the root, but your source code might be in src.
// Current: /Users/solo/project/src/routes/// Visualizing: path.join(__dirname, "..", "views", "home.html")
// 1. Start: /Users/solo/project/src/routes/// 2. "..": /Users/solo/project/src/// 3. "views": /Users/solo/project/src/views/// 4. "home.html": /Users/solo/project/src/views/home.htmlIt resolves the logic before handing the final string to the driver. Safe and OS-independent.
Extra Bits & Bytes
Section titled “Extra Bits & Bytes”Node.js Path API