Writing files with fs.writeFile
Writing is the other half of the file system, and it is the half that destroys data when it is called without thought: writeFile replaces whatever the file held, while appendFile adds to it. The third option is a flag, and the flag is what decides whether an existing file is an error, a target or a thing to keep.
The lesson writes, appends and tries an exclusive write, then puts the whole pattern together in a folder made with mkdtemp and removed in a finally block. That folder is the rule every later lesson follows: a program that writes during its run leaves nothing behind it. All functions here come from node:fs/promises, so each call is awaited.
writeFile replaces the file
writeFile(path, data) creates the file when it is missing and truncates it when it is there, so the second call in a row throws the first call away. The data may be a string or a Buffer, and a string is written as UTF-8 unless another encoding is named.
The program writes the same path three times and prints the content after each stage in quotes. JSON.stringify is used instead of a plain print because it shows the newline instead of ending the line with it.
The file write.mjs:
import { existsSync } from 'node:fs';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'write-'));
const file = join(dir, 'notes.txt');
await writeFile(file, 'first\n');
await writeFile(file, 'second\n');
console.log('the file holds:', JSON.stringify(await readFile(file, 'utf8')));
await writeFile(file, 'third\n', 'utf8');
console.log('and after another write:', JSON.stringify(await readFile(file, 'utf8')));
await rm(dir, { force: true, recursive: true });
console.log('the folder is gone:', !existsSync(dir));
node write.mjs
the file holds: "second\n"
and after another write: "third\n"
the folder is gone: true
The first line was gone after the second write, and the third call replaced the second in the same way. The encoding argument in the third call is the default written out in full, which is worth doing when a reader may not know what the default is. A program that appends to a log or a report wants appendFile instead, and that is the next section.
appendFile
appendFile opens the file for appending, creates it when it is missing and writes the new bytes after the old ones. It is the call for a log line, a row of a report and anything else that grows one piece at a time.
The program writes one line, appends two more and prints the text, the size in bytes and the number of lines. The size counts the three newlines, which is why it is larger than the number of visible characters.
The file append.mjs:
import { appendFile, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'write-'));
const file = join(dir, 'log.txt');
await writeFile(file, 'one\n');
await appendFile(file, 'two\n');
await appendFile(file, 'three\n');
const text = await readFile(file, 'utf8');
const { size } = await stat(file);
console.log('the file holds:', JSON.stringify(text));
console.log('its size in bytes:', size);
console.log('the number of lines:', text.trimEnd().split('\n').length);
await rm(dir, { force: true, recursive: true });
console.log('the folder is gone');
node append.mjs
the file holds: "one\ntwo\nthree\n"
its size in bytes: 14
the number of lines: 3
the folder is gone
The three lines are fourteen bytes: eleven letters and three newlines. The line count comes from the text and not from the file, and it is correct because the file ends with a newline and trimEnd removes only the last one.
The flag option
The flag says what to do when the file is already there. 'w' truncates and is the default, 'a' appends, and 'wx' refuses to touch an existing file and fails with EEXIST. The exclusive flag is how a program claims a file it must not overwrite, such as a lock or an output it is about to produce once.
The program writes the file, tries an exclusive write on the same path and catches the failure, then appends a line and writes again with the default flag. The last print shows what survived all four calls.
The file flags.mjs:
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'write-'));
const file = join(dir, 'data.txt');
await writeFile(file, 'original\n');
try {
await writeFile(file, 'replacement\n', { flag: 'wx' });
} catch (error) {
console.log('the exclusive write failed with:', error.code);
}
await writeFile(file, 'appended\n', { flag: 'a' });
await writeFile(file, 'replaced\n', { flag: 'w' });
console.log('the file now holds:', JSON.stringify(await readFile(file, 'utf8')));
await rm(dir, { force: true, recursive: true });
node flags.mjs
the exclusive write failed with: EEXIST
the file now holds: "replaced\n"
The exclusive write changed nothing and reported EEXIST; the append added a line; and the last call with 'w' cut the file back to one line. A read after the append would have shown both lines, which is why the order of these calls matters more than their names.
A temporary folder
mkdtemp(join(tmpdir(), 'job-')) makes a new folder under the system temporary directory and answers with its full path. The last six characters of the name are random, so two runs never share a folder, and no program can guess another one's. The cleanup goes into a finally block, so it runs even when a write in the middle throws.
The program writes two files, lists them sorted and removes the folder, then prints whether the folder is still there. It prints a boolean about the random part of the name instead of the path, because the path differs on every machine and every run.
The file tempdir.mjs:
import { existsSync } from 'node:fs';
import { mkdtemp, readdir, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { basename, join } from 'node:path';
const dir = await mkdtemp(join(tmpdir(), 'job-'));
try {
await writeFile(join(dir, 'a.txt'), 'a');
await writeFile(join(dir, 'b.txt'), 'b');
const names = (await readdir(dir)).sort();
console.log('the folder name starts with job-:', basename(dir).startsWith('job-'));
console.log('the files:', names.join(', '));
} finally {
await rm(dir, { force: true, recursive: true });
}
console.log('the folder is gone:', !existsSync(dir));
node tempdir.mjs
the folder name starts with job-: true
the files: a.txt, b.txt
the folder is gone: true
The folder was made, filled and removed inside one program, and the last line proves the removal. This is the shape every example in this part uses, and it is the shape a test uses in a project: one folder per run, a fixed set of files inside it, and nothing left when the test ends. The lesson on testing with fakes builds the same idea around a store instead of a folder.
Exercises
- Write a file with three lines and append a fourth. Print the size in bytes before and after the append.
- Try the flag 'ax' on a file that exists and print the error code. Does the call append to the file or leave it alone?
- Write a JSON file with an indentation of two spaces, read it back and print the keys. What does the indentation change in the file?
- Make a nested folder inside the temporary folder and write a file into it. Which call creates the missing parents, and which one fails?
- Move the rm call out of the finally block and make the second write fail with 'wx'. What is left on the disk?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does writeFile do to a file that already exists?
Answer
It replaces the whole content
The default flag is w, which truncates the file before writing.
-
How does appendFile differ from writeFile?
Answer
It writes after the old bytes and keeps them
The flag behind it is a, so the file keeps what it had.
-
What does this program print?
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir = await mkdtemp(join(tmpdir(), "q-")); const file = join(dir, "a.txt"); await writeFile(file, "one\n"); await writeFile(file, "two\n"); console.log(JSON.stringify(await readFile(file, "utf8"))); await rm(dir, { force: true, recursive: true });Answer
"two\n"
The second write truncated the file, so only the second text is in it.
-
Which flag refuses to write over an existing file?
Answer
wx
The x means exclusive, and the call fails with EEXIST instead of truncating.
-
What does this program print?
import { appendFile, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir = await mkdtemp(join(tmpdir(), "q-")); const file = join(dir, "a.txt"); await writeFile(file, "one\n"); await appendFile(file, "two\n"); console.log(JSON.stringify(await readFile(file, "utf8"))); await rm(dir, { force: true, recursive: true });Answer
"one\ntwo\n"
The append kept the first line and added the second after it.
-
What does mkdtemp return?
Answer
The path of a new folder with six random characters in its name
The random part is what keeps two runs from sharing a folder.
-
What does this program print?
import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; const dir = await mkdtemp(join(tmpdir(), "q-")); const file = join(dir, "a.txt"); await writeFile(file, "one\n"); try { await writeFile(file, "two\n", { flag: "wx" }); } catch (error) { console.log(error.code); } await rm(dir, { force: true, recursive: true });Answer
EEXIST
The file is already there, and the exclusive flag refuses to replace it.
-
Why do the programs print a boolean about the folder name and not the full path?
Answer
The full path differs on every machine and every run
A printed path would not match what a reader sees on their own machine.
-
What does this program print?
const text = "one\ntwo\n"; console.log(text.length);Answer
8
Six letters and two newlines make eight bytes in UTF-8.
-
Where does the removal of the temporary folder belong?
Answer
In a finally block, so it runs when a write fails too
A failure between the mkdtemp call and the end would otherwise leave the folder behind.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev