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:
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 styleUse 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
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):
JSON files
JSON is the most common format for data files. Combine readFile and writeFile with JSON.parse and JSON.stringify:
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:
| 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
Paths that work everywhere
Windows uses \ between folders and macOS/Linux use /. Never glue paths together with +; use path:
path.joincombines pieces and cleans up..and duplicate slashes.path.resolveturns 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:
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:
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
- Write a to-do list to
todos.jsonas an array of objects, then read it back, mark the first one as done and save it again. - Write a function
countWords(file)that returns how many words a text file contains. Make it return0when the file doesn't exist. - Create a folder
backup/and copy every.jsonfile from the current folder into it (usereaddir,path.extnameandcopyFile).
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?