Home / Node.js / Lesson 3

Files and a tiny HTTP server

Beginner 9 min read Lesson 3 of 6

The fs module talks to the disk. Prefer promises over callbacks:

import { readFile } from 'node:fs/promises';

const text = await readFile('notes.txt', 'utf8');
console.log(text);

Paths are relative to the current working directory (where you ran node), not always the file’s folder. Use import.meta.url + fileURLToPath when you need “next to this file.”

HTTP without a framework

import http from 'node:http';

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('Hello from Node\n');
});

server.listen(3000, () => {
  console.log('http://localhost:3000');
});

Open that URL in a browser. req.url is the path. You can branch on it, but routing by hand gets messy — that is why Express exists. Stop the process with Ctrl+C.