Creating, reading, updating, and deleting files with fs
🎯 Introduction
By the end of this article, you will be able to use file APIs to create, read, modify, and delete practice files and list directory contents.
🧱 Work in a practice directory first
node:fs provides APIs for local files and directories. Start with synchronous methods: the Sync suffix means each operation finishes before the next step, making the sequence easy to observe. Programs that continuously receive requests usually use the asynchronous approach in the next article.
Create an empty practice folder and save the code as files.mjs. First import the module:
import fs from 'node:fs'
Append the following sections in order, then run node files.mjs. Each section demonstrates one operation. Relative paths start from the current directory where you launch the command.
node-fs-demo directory you create yourself.📁 Create a directory
Prepare the parent directory before writing a file:
fs.mkdirSync('node-fs-demo', { recursive: true })
A node-fs-demo directory appears in the current directory. recursive: true creates missing parents and allows the target directory to exist already, making it suitable for repeated practice.
Success does not print a log automatically; check the file listing to confirm. Failure throws an exception.
📝 Write a file: overwrite existing content by default
fs.writeFileSync('node-fs-demo/note.txt', 'hello', 'utf8')
The three arguments are the target path, content to save, and encoding. An encoding defines how text maps to bytes. utf8 saves text using UTF-8.
After execution, note.txt contains hello. A missing file is created; an existing file is overwritten. Success returns undefined, not the file contents. Parent directories are not created automatically, which is why the previous step matters.
📖 Read a file as a string
const text = fs.readFileSync('node-fs-demo/note.txt', 'utf8')
console.log(text)
This prints hello, and text is a string. Here, utf8 specifies how to decode the file's bytes into text and should match the encoding used to save them.
Without an encoding, the result is a Buffer holding raw bytes. Specify an encoding when working with text; do not arbitrarily read images or similar files as text.
➕ Append content: keep existing text
fs.appendFileSync('node-fs-demo/note.txt', '\nNode.js', 'utf8')
The file now has two lines: hello and Node.js. Success returns undefined. Run the read statement again to verify the contents.
Use writeFileSync to replace the entire contents and appendFileSync to add to the end. Repeatedly running the append statement on its own keeps adding content.
🔍 Inspect directories and file information
First list the names in the directory:
console.log(fs.readdirSync('node-fs-demo'))
If it contains only the practice file, this prints ['note.txt']. The result is an array of names, not file contents. Do not depend on a fixed order when there are multiple entries.
Query file information to determine whether a path refers to a file or a directory:
const info = fs.statSync('node-fs-demo/note.txt')
console.log(info.isFile())
This prints true. statSync returns an object describing file status. isFile() checks for a regular file, and isDirectory() checks for a directory. Its size is measured in bytes; the file written in this example is 13 bytes long.
🏷️ renameSync: rename or move a file
fs.renameSync('node-fs-demo/note.txt', 'node-fs-demo/message.txt')
The arguments are the original and new paths. On success, the content is unchanged, the filename becomes message.txt, and note.txt no longer exists. The method returns undefined.
Different directory paths can also move a file within the same filesystem, but the target parent must exist. Moving across filesystems may fail, so this is not a general-purpose copy tool.
🗑️ Delete the file, then the empty directory
When you no longer need the practice file, delete it with unlinkSync:
fs.unlinkSync('node-fs-demo/message.txt')
On success, the file disappears and the method returns undefined. Deleting the same path again fails because the file no longer exists.
Once the directory is empty, delete it with rmdirSync:
fs.rmdirSync('node-fs-demo')
The practice directory disappears on success. If it still contains files, this call fails rather than recursively deleting its contents.
🪤 Check error codes when operations fail
A missing file commonly produces ENOENT; insufficient permissions commonly produce EACCES. Wrap synchronous calls in try/catch where they execute:
try {
fs.readFileSync('missing.txt', 'utf8')
} catch (error) {
console.log(error.code)
}
With no missing.txt present, this prints ENOENT. Decide whether to report or stop based on the specific error. Not every failure means a file is missing.
Checking existence before reading cannot prevent another program from deleting the file between those steps. Handle failure of the operation itself as well.
❓ Questions and answers
Q1: Does writing a file create its directory automatically?
No. Create the required parent directory first.
Q2: Does an empty string mean reading failed?
Not necessarily. An empty file produces an empty string. Failures are reported through exceptions or error results.
Q3: What should I check if deleting a directory fails?
Check whether it is empty, whether the path is correct, and whether the current user has permission.
🧪 Exercise
Create hello.txt in the practice directory, read it, rename it to welcome.txt, and list the directory to verify the result.
// Write your code here
🎉 Try these techniques with your own examples!
