Reading and writing files
In the browser JavaScript has no access to the disk, in Node.js it does. Working with files is the job of the built-in node:fs module (fs stands for file system). Its node:fs/promises version returns promises, so you get results with await — just as in the tutorial.
Writing a file
writeFile() creates a file or completely overwrites an existing one:
import { writeFile } from 'node:fs/promises';
await writeFile('hello.txt', 'The first blog post\n');
console.log('File written');After running it, a hello.txt file with one line appears next to the script. await can be used directly in a module, without an async function.
Reading a file
readFile() returns the contents. The second argument is the encoding: without it you get bytes (a Buffer object), not text:
import { readFile, writeFile } from 'node:fs/promises';
await writeFile('hello.txt', 'Hello, file!');
const text = await readFile('hello.txt', 'utf8');
console.log(text); // Hello, file!The example first creates the file and then reads it. Always pass utf8 when reading text.
Appending to the end
appendFile() adds text to the end of a file without erasing what is there. This is handy for an event log:
import { appendFile, readFile, writeFile } from 'node:fs/promises';
await writeFile('blog.log', 'Server started\n');
await appendFile('blog.log', 'Post 1 added\n');
await appendFile('blog.log', 'Post 2 added\n');
console.log(await readFile('blog.log', 'utf8'));Three lines are printed in order. If the file does not exist, appendFile() creates it.
Checking a file
stat() returns facts about a file: its size, modification date, whether it is a file or a folder:
import { stat, writeFile } from 'node:fs/promises';
await writeFile('hello.txt', 'Hello');
const info = await stat('hello.txt');
console.log(info.isFile()); // true
console.log(info.size); // 5The size is in bytes: each Latin letter takes one byte in UTF-8.
Main functions
| Function | What it does |
|---|---|
readFile(file, 'utf8') | Reads the whole file |
writeFile(file, text) | Creates or overwrites a file |
appendFile(file, text) | Appends to the end |
stat(file) | Facts about a file |
rename(from, to) | Renames or moves |
unlink(file) | Deletes a file |
Common mistake
Reading a file that does not exist throws an error with the code ENOENT (no such file or directory). If the file may be missing, catch it:
import { readFile } from 'node:fs/promises';
try {
await readFile('missing.txt', 'utf8');
} catch (error) {
console.log(error.code); // ENOENT
}And do not forget await: without it you get the promise Promise { <pending> } instead of the text.