Files, paths & the HTTP module
Reading and writing files with fs/promises, building paths safely and a basic HTTP server.
Node's built-in modules cover the basics without installing anything:
node:fs/promises— read and write files with promises.node:path— build file paths that work on Windows, macOS and Linux.node:http— create a web server.
The raw http module shows what a server really does: receive a request (method, URL, headers, body) and send back a response (status code, headers, body). Express, in the next lesson, builds on exactly this.
Configuration such as ports and API keys comes from environment variables (process.env.PORT), not hard-coded values.
Example code
Run with Node.js 20+// server.js
import http from "node:http";
import { readFile } from "node:fs/promises";
const PORT = process.env.PORT || 3000;
const server = http.createServer(async (req, res) => {
if (req.url === "/jobs") {
const data = await readFile("./jobs.json", "utf8");
res.writeHead(200, { "Content-Type": "application/json" });
res.end(data);
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not found");
}
});
server.listen(PORT, () => console.log("Listening on http://localhost:" + PORT));
// Then, in another terminal: curl http://localhost:3000/jobs
Output
Listening on http://localhost:3000
$ curl http://localhost:3000/jobs
[{"id":1,"title":"Node.js Developer","city":"Kochi"}]
Save the code in a file such as app.js and run node app.js. For Express lessons, run npm install express first. Names and data are fictional.
Key points
- Use node:fs/promises with await for file work.
- Use node:path to join paths.
- A server reads the request and writes a status, headers and body.
- Read config such as PORT from process.env.
Quick check
Why use process.env.PORT instead of writing 3000 in the code?
Cloud platforms assign the port through an environment variable, and keeping config outside code lets the same build run anywhere.
Practice task
Add a /health route that returns {"status":"ok"} with status 200, and make unknown routes return JSON {"error":"Not found"} with status 404.
Interview corner
Why avoid fs.readFileSync in a server?
Synchronous calls block the event loop, so no other request is served while the file is read. Use the async (promise) versions in request handlers.
What is a stream in Node?
A way to process data piece by piece instead of loading it all into memory — for example piping a large file to the response. Streams keep memory use low for big files and uploads.
Further reading
Official documentation, linked for deeper study. These are outside sites; this lesson's text is our own.
Original lesson written by the InfoparkDaily team · © 2026 InfoparkDaily · Free to learn — no paid course or subscription.