Reading and writing files
Overview
The fs (file system) module lets Node read and write files — something browser JavaScript can never do. You’ll use it for configuration, uploads, reports, logs, caches and data imports.
fs comes in three flavours. Choose the right one and your server stays fast; choose wrong and every request waits for the disk.
| Style | Import | Use it for |
|---|---|---|
| Promise | import { readFile } from 'node:fs/promises' |
everything in servers and modern code |
| Callback | import { readFile } from 'node:fs' |
older code you’ll still meet |
| Sync | import { readFileSync } from 'node:fs' |
CLI scripts and start-up code only |
This course uses the promise API.
Reading files
import { readFile } from 'node:fs/promises';
const text = await readFile('notes.txt', 'utf8'); // a string
const bytes = await readFile('photo.jpg'); // a Buffer of raw bytes
const config = JSON.parse(await readFile('config.json', 'utf8'));Without an encoding you get a Buffer — raw bytes (see Buffers and encoding). For text, pass 'utf8'.
When the file isn’t there
Reading a missing file rejects with an error whose code is ENOENT. Decide whether that’s a problem or an expected situation:
async function readOptional(file) {
try {
return await readFile(file, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') return null; // missing is fine
throw err; // anything else (permissions…) isn't
}
}Avoid checking first with existsSync and then reading — the file can disappear in between. Just try the operation and handle the error.
Writing files
import { writeFile, appendFile } from 'node:fs/promises';
await writeFile('report.txt', 'Total: 42\n'); // create or replace
await writeFile('data.json', JSON.stringify(data, null, 2)); // pretty JSON
await appendFile('app.log', `${new Date().toISOString()} started\n`);writeFile replaces the whole file. appendFile adds to the end, creating the file if needed.
Flags
The optional flag controls how the file is opened:
await writeFile('invoice-1001.pdf', pdf, { flag: 'wx' }); // fail with EEXIST if it exists| Flag | Meaning |
|---|---|
'w' |
write, create or truncate (default for writeFile) |
'wx' |
write, but fail if the file exists |
'a' |
append, create if missing |
'r' |
read (default for readFile) |
'wx' is a safe way to avoid overwriting something important, such as an invoice number that must be unique.
Writing safely
If your process crashes — or the server loses power — halfway through writeFile, you’re left with a half-written, corrupted file. For anything important, write to a temporary file first, then rename it over the real one:
import { writeFile, rename } from 'node:fs/promises';
async function saveJson(file, data) {
const tmp = `${file}.${process.pid}.tmp`;
await writeFile(tmp, JSON.stringify(data, null, 2));
await rename(tmp, file); // replaces the old file in one step
}On the same disk, rename is atomic: anyone reading the file sees either the complete old version or the complete new one, never a mix.
Copying, moving and deleting
import { copyFile, rename, rm, unlink } from 'node:fs/promises';
await copyFile('template.docx', 'contract-asha.docx');
await rename('upload.tmp', 'uploads/avatar.png'); // move or rename
await unlink('old-report.csv'); // delete a file
await rm('cache', { recursive: true, force: true }); // delete a folder and contentsforce: true means “don’t complain if it doesn’t exist”. Be careful with recursive deletes — double-check the path first, especially if any part of it comes from a variable.
Big files
readFile loads the entire file into memory. That’s fine for config files and small JSON, but reading a 4 GB log file this way will exhaust memory and crash your server.
For large files, stream them — read and process a small chunk at a time:
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
const lines = createInterface({ input: createReadStream('huge.log') });
let errors = 0;
for await (const line of lines) {
if (line.includes('ERROR')) errors++;
}
console.log(`${errors} errors`);This uses a tiny, constant amount of memory however large the file is. The Streams chapter covers this properly.
File handles
For fine-grained control — reading part of a file, or writing many times without reopening — open a file handle:
import { open } from 'node:fs/promises';
const file = await open('audit.log', 'a');
try {
await file.write('user 7 logged in\n');
await file.write('user 7 changed password\n');
} finally {
await file.close(); // always close what you open
}Files in a real app
Writing files to the server’s disk works well for scripts, logs and caches. For user data in production, be careful: in containers and cloud platforms, the disk is often wiped on every deployment, and several copies of your app don’t share one disk. Store user data in a database, and uploaded files in object storage such as Amazon S3 or Cloudflare R2 — you’ll see this in File uploads.
Rule of thumb: small file →
readFile/writeFile; big file → streams; important file → temp file + rename.
A tiny JSON database
Write loadTodos() and addTodo(text) that store todos in todos.json. loadTodos returns [] if the file doesn't exist yet. addTodo should write safely: save to a temporary file first, then rename it over the real one.
import { readFile, writeFile, rename } from 'node:fs/promises';
const FILE = new URL('./todos.json', import.meta.url);import { readFile, writeFile, rename } from 'node:fs/promises';
import { randomUUID } from 'node:crypto';
import { fileURLToPath } from 'node:url';
const FILE = fileURLToPath(new URL('./todos.json', import.meta.url));
export async function loadTodos() {
try {
return JSON.parse(await readFile(FILE, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') return [];
throw err;
}
}
export async function addTodo(text) {
const todos = await loadTodos();
todos.push({ id: randomUUID(), text, done: false });
const tmp = `${FILE}.${process.pid}.tmp`;
await writeFile(tmp, JSON.stringify(todos, null, 2));
await rename(tmp, FILE); // atomic: readers never see a half-written file
return todos;
}Summary
- Use
node:fs/promiseswithawaitin servers; sync versions are for scripts and start-up. - Pass an encoding (
'utf8') to get a string instead of a Buffer. writeFilereplaces a file;appendFileadds to the end;flag: 'wx'refuses to overwrite.- Handle
ENOENTand other error codes explicitly. - Write to a temporary file and
renameit for crash-safe saves; stream large files instead of loading them.