Thuta Learning
Node.js
ExercisesWeb DevelopmentBeginner

Practice: Core Modules (fs, path, http)

Node.jsLesson 2740 min

What you'll walk away with

  • Write, append to and read a file with fs/promises, and explain how the callback version differs
  • Build paths that work on both Windows and Linux with path.join, basename and extname
  • Write an http.createServer() handler that checks method and url for one route plus a 404
  • Clean up temp folders and servers after practice, and handle error codes such as ENOENT

Explain it simply

Explain it simply

This lesson teaches nothing new. It is practice: you write by hand what you read in the fs, path and http lessons. Reading a driving manual is not the same as driving on a real road. Only when you run the code yourself do questions like "where did my file actually go?" or "why does the server not stop?" come up, and those answers are the ones that stick.

You will work through three tasks in order: write a file and read it back, build paths safely, and build a tiny server that answers requests.

Problem → Why → Solution

The problem: a script that only works on one machine

The script below works on the developer's Mac but has three problems elsewhere. It glues strings with 'data' + '/' + 'todo.txt', mixing separators with Windows' \. The path is relative, so the file lands not next to the script but in whatever folder node was started from (the current working directory), and if that folder has no data directory you get ENOENT.

Finally, it listens on port 4000 and never closes, so inside a test the process never exits, and a second run fails with EADDRINUSE.

practice-draft.js
const fs = require('fs');
const http = require('http');

fs.writeFile('data' + '/' + 'todo.txt', 'Learn Node.js', () => {}); // error ignored

http.createServer((req, res) => {
  res.end(new Date().toISOString());          // every URL gets 200
}).listen(4000);                                // fixed port, never closed

Why it happens

Node resolves relative paths against process.cwd(), not the script's location. An err that is never checked in a callback disappears silently. And a listening server tells the event loop there is still work to do, so the process never exits.

Core concept: three tasks, three rules

Each task exercises one module, and each comes with one rule to remember.

Task 1 (fs): always check the error

fs offers three API styles: callback (fs.writeFile(file, data, cb)), promise (require('node:fs/promises')) and sync (fs.writeFileSync). In the callback style the first argument is err and you check it with if (err). With promises you await the call and catch errors with try/catch or .catch(). For steps that must happen in order, such as write then read, await reads far more easily than nested callbacks.

Task 2 (path): never type the separator yourself

path.join('data', 'logs', 'app.log') returns data/logs/app.log on Linux and macOS and data\logs\app.log on Windows. path.sep is the current OS's separator, path.basename gives the last part (app.log) and path.extname the extension (.log). To build paths relative to the script's own folder, use path.join(__dirname, 'data').

Task 3 (http): close what you open

The http.createServer() handler runs for every request, and you check req.method and req.url yourself; there is no router as in Express. Note that req.url includes the query string, so /time?tz=utc is not equal to '/time'; parse it with new URL(req.url, 'http://localhost') when queries matter. Each response gets its status and headers from writeHead() and is finished with end(). In a practice script, take a free port with listen(0), and call server.close() as soon as you are done. Remove the temp folder with fs.rm() as well.

callback-style.js
const fs = require('node:fs');
const path = require('node:path');
const os = require('node:os');

const file = path.join(os.tmpdir(), 'callback-demo.txt');
fs.writeFile(file, 'written with a callback', 'utf8', (err) => {
  if (err) return console.error('Write failed:', err.message);
  fs.readFile(file, 'utf8', (err2, data) => {
    if (err2) return console.error('Read failed:', err2.message);
    console.log('Read back:', data);
    fs.unlink(file, () => {}); // tidy up
  });
});

The snippet above is Task 1 in callback style. The read has to live inside the write's callback, so every extra step adds another level of indentation. The example rewrites the same flow with await. Both styles are correct and you will meet both in real code, so it is worth being able to read either one.

Mental model: open, use, close
  1. Take a temp folder and port 0
  2. Build file paths with path
  3. Await writes, reads and requests
  4. Close the server, delete the folder

For every resource you open (file, folder, server), you should be able to point at the line that closes it.

General pattern

javascript
const fs = require('node:fs/promises');
const path = require('node:path');
const http = require('node:http');

await fs.writeFile(path.join(dir, 'name.txt'), text, 'utf8');
const content = await fs.readFile(path.join(dir, 'name.txt'), 'utf8');

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/route') return send(res, 200, body);
  send(res, 404, 'Not Found');                  // send = writeHead() + end()
});

Use fs/promises with await and build every path with path.join. The http handler checks method and url and falls back to a 404.

All three tasks in one script

The script runs the three tasks in order inside one async main() function. Files go into a new folder under the OS temp directory instead of your project, so nothing is left behind. Because /time changes on every run, the output prints whether it is a valid date rather than the time itself.

practice.js
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const http = require('node:http');

async function main() {
  // Task 1: write a file and read it back, inside a throwaway temp folder
  const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'practice-'));
  const file = path.join(dir, 'todo.txt');
  await fs.writeFile(file, 'Learn Node.js modules\n', 'utf8');
  await fs.appendFile(file, 'Practise fs, path and http\n', 'utf8');
  const text = await fs.readFile(file, 'utf8');
  console.log('Task 1 lines:', text.trim().split('\n'));

  // Task 2: build paths with the path module, never by gluing '/'
  const logPath = path.join('data', 'logs', 'app.log');
  console.log('Task 2 parts:', logPath.split(path.sep));
  console.log('  base:', path.basename(logPath), '| ext:', path.extname(logPath));

  // Task 3: a tiny http server with one route and a 404
  const server = http.createServer((req, res) => {
    if (req.method === 'GET' && req.url === '/time') {
      res.writeHead(200, { 'Content-Type': 'application/json' });
      res.end(JSON.stringify({ now: new Date().toISOString() }));
      return;
    }
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Not Found');
  });
  await new Promise((resolve) => server.listen(0, resolve));
  const base = `http://localhost:${server.address().port}`;

  const timeRes = await fetch(`${base}/time`);
  const { now } = await timeRes.json();
  const valid = !Number.isNaN(Date.parse(now));
  console.log('Task 3 /time:', timeRes.status, 'valid date:', valid);
  const missing = await fetch(`${base}/nope`);
  console.log('Task 3 /nope:', missing.status, await missing.text());

  server.close();
  await fs.rm(dir, { recursive: true, force: true });
}

main().catch((err) => {
  console.error('Practice failed:', err.message);
  process.exitCode = 1;
});

Code breakdown

  1. Throwaway folderconst dir = await fs.mkdtemp(path.join(os.tmpdir(), 'practice-'));

    mkdtemp adds random characters after the prefix and creates a fresh folder, so each run starts clean and never mixes with files from an earlier run.

  2. Append, then readawait fs.appendFile(file, 'Practise fs, path and http\n', 'utf8');

    writeFile creates or overwrites the file, while appendFile adds to the end. That is why two lines come back.

  3. OS-neutral outputconsole.log('Task 2 parts:', logPath.split(path.sep));

    Printing the path string directly would differ between Windows and Linux. Splitting on path.sep gives ['data', 'logs', 'app.log'] on every OS.

  4. Manual routingif (req.method === 'GET' && req.url === '/time') {

    The http module has no router, so you compare method and url yourself. The return keeps execution from falling through to the 404 code.

  5. Waiting for listenawait new Promise((resolve) => server.listen(0, resolve));

    listen() uses a callback, so it is wrapped in a Promise and awaited; fetch only runs once the server is ready.

  6. Clean upawait fs.rm(dir, { recursive: true, force: true });

    server.close() and fs.rm() undo everything the script opened, so the process exits cleanly.

You should see
Task 1 lines: [ 'Learn Node.js modules', 'Practise fs, path and http' ]
Task 2 parts: [ 'data', 'logs', 'app.log' ]
  base: app.log | ext: .log
Task 3 /time: 200 valid date: true
Task 3 /nope: 404 Not Found

Check yourself, then stretch

Write each task yourself before looking at the example, then compare with the table below. The middle column is the check that tells you a task is done; the right column is a stretch exercise for when you have time left.

TaskYou are done whenStretch goal
1. fsBoth lines read back and the folder is goneCatch ENOENT for a missing file and print a message
2. pathThe output is identical on every OSPrint the result of path.parse()
3. http/time is 200, others 404, and the process exitsReject POST /time with 405

In real projects

In real projects

Even in Express projects you meet these three modules every day. Saving uploaded files to disk, reading config files, writing logs and creating folders in build scripts are all jobs for fs and path. Express itself is built on the http module, and app.listen() returns an http server.

Tests use this lesson's pattern constantly: each test takes its own folder with mkdtemp, starts its own server on port 0, and cleans up afterwards, so tests can run in parallel without disturbing each other. When CI runs Linux and a developer runs Windows, the path module lets the same code work in both places. A forgotten server.close() is also one of the most common reasons a test suite finishes its work and then hangs.

Common mistakes

Common mistakes

Assuming a relative path means the script's folder

fs.readFile('config.json') looks in the folder node was started from. Run node src/app.js from the project root and src/config.json is not found. For files that belong next to the script, use path.join(__dirname, 'config.json').

Forgetting res.end()

If a branch calls writeHead() but never end(), the client keeps waiting for the response to finish and the browser spins forever. Check that every branch ends the response, including the 404 at the bottom.

Treating every error as "file not found"

Returning null for any error in a catch also hides real problems such as a permission error (EACCES). Treat only err.code === 'ENOENT' as "missing" and rethrow everything else.

Best practices

Best practices

  • Load core modules with the node: prefix, as in require('node:fs'), so they never clash with an npm package of the same name
  • Write practice files under os.tmpdir() and keep your project folder clean
  • Use port 0 instead of a fixed port and read the real one from server.address().port

Mini challenge

Notes server: Task 4 plus a /hello route

Pull the file-reading logic into a readNoteSafe(file) function (Task 4). Then give an http server two routes: GET /hello (a JSON message) and GET /notes/<name> (reads <name>.txt from a temp folder). Guard against requests such as /notes/..%2Fsecret that try to escape the folder.

  • readNoteSafe() returns null for ENOENT and rethrows any other error
  • /hello answers 200 with { message: 'Hello Node.js' }
  • /notes/<name> decodes with decodeURIComponent and strips folders with path.basename
  • A missing note gets a 404 JSON; afterwards close the server and delete the temp folder
notes-server.js
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const http = require('node:http');

async function readNoteSafe(file) {
  // TODO: return the text; null on ENOENT; rethrow anything else
}

function sendJson(res, status, body) {
  // TODO: writeHead with Content-Type application/json, then end(JSON)
}

async function main() {
  // TODO: mkdtemp a folder and write todo.txt into it
  // TODO: createServer: /hello, /notes/<name> (basename!), else 404
  // TODO: listen(0), fetch four URLs, print status + body, close, rm folder
}

main();

Expected: /hello and /notes/todo answer 200 ("Buy rice"), /notes/shopping answers 404, and /notes/..%2Fsecret answers 404 with "No note named secret".

Show hint

req.url.slice('/notes/'.length) gives the name part. decodeURIComponent('..%2Fsecret') is '../secret', and path.basename('../secret') is 'secret', so the request can no longer leave the folder.

Show solution
notes-server.js
const fs = require('node:fs/promises');
const path = require('node:path');
const os = require('node:os');
const http = require('node:http');

// Returns the file's text, or null when it does not exist
async function readNoteSafe(file) {
  try {
    return await fs.readFile(file, 'utf8');
  } catch (err) {
    if (err.code === 'ENOENT') return null;
    throw err; // permission problems etc. are real errors
  }
}

function sendJson(res, status, body) {
  res.writeHead(status, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify(body));
}

async function main() {
  const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'notes-'));
  await fs.writeFile(path.join(dir, 'todo.txt'), 'Buy rice', 'utf8');

  const server = http.createServer(async (req, res) => {
    if (req.url === '/hello') return sendJson(res, 200, { message: 'Hello Node.js' });

    if (req.url.startsWith('/notes/')) {
      // basename() strips any folders, so "../secret" becomes "secret"
      const name = path.basename(decodeURIComponent(req.url.slice('/notes/'.length)));
      const text = await readNoteSafe(path.join(dir, `${name}.txt`));
      if (text === null) return sendJson(res, 404, { error: `No note named ${name}` });
      return sendJson(res, 200, { name, text });
    }
    sendJson(res, 404, { error: 'Not Found' });
  });

  await new Promise((resolve) => server.listen(0, resolve));
  const base = `http://localhost:${server.address().port}`;
  for (const url of ['/hello', '/notes/todo', '/notes/shopping', '/notes/..%2Fsecret']) {
    const res = await fetch(base + url);
    console.log(url, res.status, JSON.stringify(await res.json()));
  }
  server.close();
  await fs.rm(dir, { recursive: true, force: true });
}

main().catch((err) => {
  console.error('Failed:', err.message);
  process.exitCode = 1;
});

Quick quiz 1 / 3

You run node scripts/report.js from the project root. Which file does fs.readFile('data.csv') inside report.js look for?

Quick quiz 2 / 3

What does path.join('data', 'logs', 'app.log') return on Windows?

Quick quiz 3 / 3

What happens if you delete the server.close() line from the example script?

What to remember

  • fs/promises with await keeps ordered steps like write-then-read easy to read
  • Build every path with path.join, and use __dirname for paths relative to the script
  • An http handler checks method and url itself and must call res.end() on every branch
  • In practice scripts and tests, use mkdtemp and port 0, then clean up with server.close() and fs.rm()

Node.js API index — Node.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice: Core Modules (fs, path, http) | Thuta Learning