Writing Files, File Operations, Metadata and Directories in Node
Write files whole, appended, streamed or at byte positions; open flags like "a" and "wx"; truncate and fsync; atomic saves with rename; copy, move, delete and cp; stat metadata and permissions; mkdir, readdir, recursive listings, opendir, glob, rm and watching files.
kvi5hnuCode Sprout team member7 min readOn this page
Article 128 covered reading. This article covers the rest of everyday file system work: writing, copying, moving and deleting files, reading metadata, and working with directories. All examples use node:fs/promises; every function also has callback and Sync variants (article 128).
Writing files
Like reading, writing comes in three styles:
- All at once:
writeFile(path, data)creates the file, or replaces it if it exists.datais a string (UTF-8 unless you pass an encoding) or a Buffer.appendFile(path, data)adds to the end instead, creating the file if needed. - Streaming:
fs.createWriteStream(path)for data produced piece by piece, respecting backpressure (article 127). - Positioned: open a
FileHandleand callhandle.write(data, position)to write at chosen byte positions.
const fsp = require("node:fs/promises");
const os = require("node:os");
const path = require("node:path");
async function main() {
const dir = await fsp.mkdtemp(path.join(os.tmpdir(), "write-"));
const log = path.join(dir, "app.log");
await fsp.writeFile(log, "started\n"); // create or replace
await fsp.appendFile(log, "request 1\n"); // add to the end
await fsp.writeFile(log, "request 2\n", { flag: "a" }); // same as appendFile
console.log(JSON.stringify(await fsp.readFile(log, "utf8")));
// "wx": create a new file, but fail if it already exists
try {
await fsp.writeFile(log, "oops", { flag: "wx" });
} catch (err) {
console.log("wx refused:", err.code);
}
// Writing at specific positions through a FileHandle
const handle = await fsp.open(path.join(dir, "grid.txt"), "w+");
try {
await handle.write(".........."); // 10 dots
await handle.write("XY", 4); // overwrite bytes 4 and 5
await handle.truncate(8); // cut the file to 8 bytes
await handle.sync(); // force data to disk (fsync)
} finally {
await handle.close();
}
console.log(await fsp.readFile(path.join(dir, "grid.txt"), "utf8"));
// Save JSON atomically: write a temporary file, then rename over the target
async function saveJSON(file, data) {
const tmp = `${file}.${process.pid}.tmp`;
await fsp.writeFile(tmp, JSON.stringify(data, null, 2));
await fsp.rename(tmp, file); // readers see the old or the new file, never half
}
const settings = path.join(dir, "settings.json");
await saveJSON(settings, { theme: "dark", fontSize: 14 });
console.log(JSON.parse(await fsp.readFile(settings, "utf8")));
console.log((await fsp.readdir(dir)).sort());
await fsp.rm(dir, { recursive: true });
}
main();
"started\nrequest 1\nrequest 2\n"
wx refused: EEXIST
....XY..
{ theme: 'dark', fontSize: 14 }
[ 'app.log', 'grid.txt', 'settings.json' ]
Open flags
fsp.open(path, flags) and the flag/flags option of writeFile and createWriteStream say how the file is opened:
| Flag | Meaning |
|---|---|
"r" (default for open) | read; the file must exist |
"r+" | read and write; the file must exist |
"w" (default for writeFile) | write; create, or truncate to empty if it exists |
"w+" | like "w", but also readable |
"a" / "a+" | append (create if needed); every write goes to the end |
"wx", "ax" | like "w"/"a", but fail with EEXIST if the file exists |
The x flags make "create only if new" a single atomic step, which is safer than checking with existsSync first: another process could create the file between your check and your write. Lock files and unique output files use "wx".
truncate and fsync
truncate(path, length) (or handle.truncate) cuts a file to length bytes, or extends it with zero bytes if it's shorter. Length 0 empties it.
When a write call completes, Node has handed the data to the operating system, which may still hold it in memory before writing it to disk. After a power failure, the most recent writes can be lost. handle.sync() (the fsync system call) forces the data onto the disk. Databases and anything that must not lose acknowledged data call it; for ordinary files it's rarely needed, and it's slow.
Saving safely: write, then rename
writeFile on an existing file first empties it, then writes. If the program crashes or the disk fills up in between, the file is left empty or half written: a corrupted settings file that breaks the next start.

The standard fix, saveJSON in the example, writes the complete content to a temporary file in the same directory, then renames it over the target. A rename within one file system is atomic, so every reader sees either the complete old file or the complete new one. (For maximum durability, also sync() the temporary file before renaming.)
Copying, moving and deleting
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const os = require("node:os");
const path = require("node:path");
async function main() {
const root = await fsp.mkdtemp(path.join(os.tmpdir(), "ops-"));
const p = (...parts) => path.join(root, ...parts);
await fsp.mkdir(p("src", "lib"), { recursive: true }); // creates parents; no error if present
await fsp.writeFile(p("src", "index.js"), "console.log('hi');\n");
await fsp.writeFile(p("src", "lib", "math.js"), "exports.add = (a, b) => a + b;\n");
await fsp.writeFile(p("README.md"), "# demo\n");
// Copy, refusing to overwrite
await fsp.copyFile(p("README.md"), p("README.bak"), fs.constants.COPYFILE_EXCL);
try {
await fsp.copyFile(p("README.md"), p("README.bak"), fs.constants.COPYFILE_EXCL);
} catch (err) {
console.log("copy refused:", err.code);
}
await fsp.rename(p("README.bak"), p("src", "README.bak")); // move
await fsp.unlink(p("src", "README.bak")); // delete a file
await fsp.cp(p("src"), p("backup"), { recursive: true }); // copy a whole tree
// Metadata
const st = await fsp.stat(p("src", "index.js"));
console.log(st.isFile(), st.isDirectory(), st.size, st.mtime instanceof Date);
await fsp.chmod(p("src", "index.js"), 0o600);
console.log("mode:", ((await fsp.stat(p("src", "index.js"))).mode & 0o777).toString(8));
// Listing: names, entries with types, and a whole tree
console.log((await fsp.readdir(root)).sort());
const entries = await fsp.readdir(p("src"), { withFileTypes: true });
console.log(entries.map((e) => `${e.name}${e.isDirectory() ? "/" : ""}`).sort());
const all = await fsp.readdir(root, { recursive: true });
console.log(all.map((f) => f.split(path.sep).join("/")).sort());
// Glob patterns
const matches = [];
for await (const f of fsp.glob("**/*.js", { cwd: root })) matches.push(f.split(path.sep).join("/"));
console.log(matches.sort());
await fsp.rm(root, { recursive: true, force: true }); // delete the tree
console.log("exists after rm:", fs.existsSync(root));
}
main();
copy refused: EEXIST
true false 19 true
mode: 600
[ 'README.md', 'backup', 'src' ]
[ 'index.js', 'lib/' ]
[
'README.md',
'backup',
'backup/index.js',
'backup/lib',
'backup/lib/math.js',
'src',
'src/index.js',
'src/lib',
'src/lib/math.js'
]
[
'backup/index.js',
'backup/lib/math.js',
'src/index.js',
'src/lib/math.js'
]
exists after rm: false
copyFile(src, dest, mode?)copies one file.fs.constants.COPYFILE_EXCLrefuses to overwrite;COPYFILE_FICLONEasks for a copy-on-write clone on file systems that support it.cp(src, dest, { recursive: true })copies a whole directory tree.rename(old, new)moves or renames. It silently replaces an existing target, and it only works within one file system; across devices it fails withEXDEV, and you must copy and then delete.unlink(path)deletes a file. The name comes from Unix: a file is removed when its last link (directory entry) is removed.linkandsymlinkcreate hard and symbolic links.rm(path, { recursive: true, force: true })deletes a file or a whole directory tree;forceignores a missing path. Be careful with paths built from variables or user input: there's no undo.
Metadata
stat(path) returns a Stats object:
isFile(),isDirectory(),isSymbolicLink()(only meaningful withlstat, which doesn't follow links).sizein bytes.mtime(last modified),atime(last accessed),ctime(metadata last changed) andbirthtime(created, where supported), allDateobjects.mode(type and permission bits),uidandgid(owner).
mode & 0o777 extracts the Unix permission bits, written in octal: 0o644 is "owner can read and write; others can read", 0o600 is "only the owner can read and write" (right for files holding secrets), and 0o755 adds execute permission for scripts and directories. Change them with chmod, and the owner with chown. Windows supports only a read-only flag. To test permissions, access(path, fs.constants.R_OK) rejects if the file isn't readable, but as with exists, prefer simply attempting the operation and handling the error.
Directories
mkdir(path, { recursive: true })creates a directory and any missing parents, and doesn't fail if it already exists.mkdtemp(prefix)creates a uniquely named directory, ideal for temporary work, as every example here does.readdir(path)returns entry names (not full paths).{ withFileTypes: true }returnsDirentobjects withname,parentPathandisFile()/isDirectory(), saving astatcall per entry.{ recursive: true }lists a whole tree, with paths relative to the starting directory. Entries come in no guaranteed order, so sort when order matters.glob(pattern, { cwd })(Node 22 and later) finds files matching patterns like**/*.jsand is an async iterable.rmdirremoves an empty directory;rmwithrecursiveremoves anything.- For directories with very many entries,
opendir(path)returns aDirthat you read one entry at a time, without building a huge array:
const dir = await fsp.opendir("/var/log");
for await (const entry of dir) { // the Dir closes itself when the loop ends
if (entry.isFile()) console.log(entry.name);
}
Watching for changes
fs.watch(path, { recursive: true }) reports changes to files and directories, and fsp.watch returns an async iterator of { eventType, filename } events. It relies on operating system facilities, so the details vary between platforms; events may arrive twice, and renames show up as "rename". Tools such as file watchers in build systems, and node --watch itself (article 122), are built on it. For production use, libraries like chokidar smooth over the platform differences.
Common questions
How do I check whether a file exists?
fs.existsSync(path) is fine in scripts. In asynchronous code, try the operation you actually want and handle ENOENT; for a pure check, await fsp.access(path).then(() => true, () => false). A separate check can be out of date by the time you act on it.
Why does rename fail with EXDEV?
The source and destination are on different file systems (for example, the system temporary directory and a mounted volume). rename can't move data between devices; copy the file and then delete the original. That's also why an atomic-save temporary file must be in the same directory as the target.
readdir returned names; why can't I open them?
readdir returns names relative to the directory, so they don't work from the current directory. Join them with the directory path: path.join(dir, name), or use entry.parentPath with withFileTypes.
Summary
writeFilereplaces,appendFileappends, write streams handle large output, andFileHandle.write(data, position)writes at offsets. Flags such as"a"and"wx"control creation and overwriting.truncateresizes;syncforces data to disk; write a temporary file andrenameit for atomic saves.copyFile,cp,rename,unlink,rmcopy, move and delete;statreturns type, size, times and permissions.mkdirwithrecursive,mkdtemp,readdir(withwithFileTypesandrecursive),opendir,globandwatchwork with directories.
Practice Questions
What's the difference between writeFile(path, data, { flag: "wx" }) and checking existsSync(path) before calling writeFile?
Answer
"wx" creates the file only if it doesn't exist, in a single atomic operation, and rejects with EEXIST otherwise. With a separate check, another process can create the file between the check and the write, and the write would then overwrite it.
Write an async function totalSize(dir) that returns the total size in bytes of all files under dir, including subdirectories.
Answer
const fsp = require("node:fs/promises");
const path = require("node:path");
async function totalSize(dir) {
let total = 0;
for (const entry of await fsp.readdir(dir, { withFileTypes: true, recursive: true })) {
if (entry.isFile()) {
total += (await fsp.stat(path.join(entry.parentPath, entry.name))).size;
}
}
return total;
}
Why do programs save important files by writing a temporary file and renaming it?
Answer
Writing the target directly empties it first, so a crash midway leaves a corrupt file. Renaming a completed temporary file over the target is atomic, so the file is always either the complete old version or the complete new one.
What does (stat.mode & 0o777).toString(8) returning "644" mean?
Answer
The owner can read and write the file (6), and the group and everyone else can only read it (4 and 4).
Previous: Node Process and OS Details, File Paths and Reading Files
Next: HTTP in Node: Servers, Routing, Static Files and Clients

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.