Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

NO
Node.js & Express
0/13 completed
Beginner
What is Node.js?Modules and npmWorking with filesCallbacks, promises and the event loop
Intermediate
Events and streamsYour first HTTP serverExpress basicsRouting and middlewareConnecting a database
Advanced
Validation and configurationAuthentication with JWTTesting APIs
Pro
Deploying Node apps to production
Tracks / Node.js & Express / Beginner

Working with files

Reading and writing files is one of the first things a server or script needs: configuration, logs, uploaded images, CSV exports, JSON data. Node's built-in fs (file system) module does all of it, and path builds file paths that work on every operating system.

Three styles of the same API

fs offers every operation in three flavours:

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

fs.readFileSync('notes.txt', 'utf8');                 // 1. synchronous: blocks until done
fs.readFile('notes.txt', 'utf8', (err, text) => {});  // 2. callback: the original async style
await readFile('notes.txt', 'utf8');                  // 3. promise: modern async style

Use the promise API (node:fs/promises) with await in servers and most programs. The synchronous versions are fine in small scripts and at startup (reading a config file once), but in a web server they freeze every other request while the disk works.

Writing and reading text

Node.js · editable

The 'utf8' argument tells Node to decode the bytes as text. Without it you get a Buffer, Node's type for raw bytes (useful for images and other binary files):

Node.js · editable

JSON files

JSON is the most common format for data files. Combine readFile and writeFile with JSON.parse and JSON.stringify:

Node.js · editable

JSON.stringify(value, null, 2) indents the output with two spaces, so the file is easy for humans to read.

When things go wrong

File operations fail all the time: the file doesn't exist, the folder is missing, you don't have permission. Node reports it with an error that has a code:

Node.js · editable
Code Meaning
ENOENT No such file or directory
EEXIST It already exists
EISDIR It's a directory, but you treated it as a file
EACCES / EPERM Permission denied
ENOTEMPTY Tried to remove a folder that isn't empty

Check err.code rather than the message: messages can change, codes don't.

Folders

Node.js · editable

Paths that work everywhere

Windows uses \ between folders and macOS/Linux use /. Never glue paths together with +; use path:

Node.js · editable
  • path.join combines pieces and cleans up .. and duplicate slashes.
  • path.resolve turns a path into an absolute path, starting from the current working directory.

Paths relative to your code

readFile('data.json') looks in the current working directory, which is wherever the user ran node from, not necessarily where your script lives. To load a file that sits next to your code, build the path from import.meta.dirname:

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

const templatePath = path.join(import.meta.dirname, 'templates', 'email.html');
const template = await readFile(templatePath, 'utf8');

(In CommonJS files the same value is called __dirname.)

Big files: streams

readFile loads the whole file into memory. That's fine for a few megabytes, but a 5 GB log file would exhaust the memory. Streams process data in chunks as it arrives. Here, Node reads a file line by line:

Node.js · editable

This uses the same small amount of memory whether the file has 5 lines or 50 million. Streams get their own lesson later in this track.

Practice

  1. Write a to-do list to todos.json as an array of objects, then read it back, mark the first one as done and save it again.
  2. Write a function countWords(file) that returns how many words a text file contains. Make it return 0 when the file doesn't exist.
  3. Create a folder backup/ and copy every .json file from the current folder into it (use readdir, path.extname and copyFile).
✎ Check your understanding

1.Why prefer fs/promises over readFileSync in a web server?

2.Which error code means the file doesn't exist?

3.What's the safe way to build a file path?

← Modules and npm