Mastering with Files
To help us cement concepts like async, event loop, process.argv from preceeding lessons, we would learn and build simple programs around files. At the end of this lesson, you should have mastered file operations such as reading, writing to files and directory.
One of the popular targets of read and write operations is the file system. The use of files and file system can be seen everywhere, from when uploading files ( images, documents, audios, videos) to saving a PDF document, installing an app or open a photo from downloads. Even if you don't notice, you're interacting with a file system all the time, it is only important that we thoroughly understand them.
There are two main built-in modules for handling files in Node, fs complemented by path. Aside these two, other useful Node.js modules for working with files include os, url, stream, zlib, cryprto, buffer, child_process and readline. Our focus will be on fs and path before covering the rest in later in this lesson.
Asynchronous and synchronous functions
Usually working with fs and path for the first time can feel like a lot. There are many methods for doing same thing: fs.readFile(), fs.readFileSync() and fs.promises.readFile(). There are usually multiple variants of an operation in these modules, but thankfully are broadly categorized into two:
- Async [, nonblocking, callback-based, and asynchronous such as
fs.readFile()&fs.promises.readFile()] - Sync [, synchronous blocking variant such as
fs.readFileSync()]
Both versions exist out of the box from Node. In version 10+, they added a promise-based API too ( that of likes of fs.promises.readFile()). While the Sync versions returns a value, the Async's are handled with callbacks ( or promises).
Actions with files and directories
There are common actions that are performed on files and directories such as Create, Read, Write, Update and Watch. Others are Delete, Rename, Move, Copy.
Auxiliary actions are for getting more information about the file or directory such as to check existence, confirm if you have permissions to a certain action, get stat ( size, creation date, modification date) etc
Read
Node allows you to a read file all at once or in stream ( in bytes). There is a classic low level way [, method, API] of reading a file and high level alternatives for doing them.
The low level API (fs.read) helps you understand and appreciate how their high level counterparts work (fs.readFile & fs.createReadStream).
- Read all at once
Ensure on the same directory you have the read-file-as-txt.js also has a msg.txt file. Our goal is to read the msg.txt all at once and print to the std out after we are done.
This approach is perfect for small files (or directories).
jsfs.readFile('msg.txt', 'utf8', (err, data)=> {
if(err){
console.error('Error reading file:', err.message);
return;
}
console.log(data);
})
Key notes:
- The second property of the readFile function
(path, **encoding [, utf8]**, callback)is important to turn the returned value to string. If not,i.e you didreadFile(path, callback), JavaScript returns a Buffer. - In most cases,the first argument for methods in the
fsmodule is the file path.
We can rewrite the callback style to use its promise variant.
jsconst fs = require('fs/promises');
async function main(){
try {
// see the second parameter is the encoding that converts our Buffer to string
const content = await fs.readFile('msg.txt', 'utf8');
console.log(content);
}catch(err){
console.error('Failed:', err.message);
}
}
Our last example will show how to read a directory, wrapping up reading a file/directory all at once. This example combines reading a directory before reading the files inside it while excluding sub-directories.
jsconst fs = require('fs/promises');
const path = require('path');
async function readAllFilesInFolder(folderPath){
const linkPaths = await fs.readdir(folderPath);
for(const lPath of linkPaths){
const lStats = await fs.lstat(lPath), isFile = lStats.isFile();
if(!isFile)continue
const content = await fs.readFile(lPath, 'utf8');
console.log(content +`\n****${lPath}******\n`)
}
}
readAllFilesInFolder('./');
Playground with the low level API
We are going to move into reading a file using fs.read that can be elaborated as fs.read(fd, buffer, offset, length, position, callback). With this method, we'll dablle into details from opening, to operating and closing the file.
To use fs.read:
- You first need to open the file, and
- You must close it with fs.close
jsimport fs from 'fs';
const filename = 'note.txt'
fs.open(filename, (err, fd)=> {
if(err) throw err;
fs.fstat(fd, (err, stats)=> {
if(err) throw err;
const size = stats.size;
const buffer = new Buffer.alloc(size);
fs.read(fd, buffer, 0, size, 0, (err, data, content)=> {
if(err) throw err;
fs.close(fd, (err)=> {
if(err) throw err;
console.log({
content: content.toString()
})
}
)
})
})
})
Like it was previously mentioned, fs.read is a verbose and low level method that shouldn't be used except you know what are doing. The code above can be rewritten with fs.readFile or fs.createReadStream, less verbose and simple.
jsimport fs from 'node:fs'
const filename = process.argv[2];
const fsStream = fs.createReadStream(filename);
fsStream.on('data', data => { console.log(data) });
fsStream.on('error', err => { throw err })
Write | Update | Create | Watch
Similar to what we established with the read section, the simplest way to write a file is to use the high level APIs fs.writeFile(path, data, [encoding], (err)), fs.writeFileSync(filename, [data, ...options]), fs.createWriteStream instead of low level APIs like fs.write. Going forward, We are going to neglect these low level APIs. You can go learn more about them by yourself.
In Node.js, "updating" a file can mean many things:
- read an existing content, make changes and write it back;
- replace ( or overwrite) the entire file ( or content);
- or append new content.
To overwrite the entire file, use the fs.writeFile method. To append new content to the file, use fs.appendFile. And to Read, Modify, Write back, first use the fs.readFile to read the content, modify the read content and implement fs.writeFile in its callback.
To create a new file is relatively easier with fs.writeFile, if the file do not exist, it will create it for you.
Reading and Writing Files Asynchronously
Reading and writing files are fundamental operations in programming.There are two approaches to reading and writing files in Node:
- The simplest, to read in or write out the file at once. It is also called Buffered or Synchronous I/O.
- The other approach reads and writes by creating Streams or staging content in Buffered Chunks.
Read/Writing a File all at Once
This approach loads the entire file into memory before processing it.
How it works
- The whole file is read into a temporary storage in RAM (buffer).
- The program then works with the complete data
- After doing whatever with the data, the entire file is written back (if modified)
bashimport fs from "node:fs";
// Reading a file all at once
fs.readFile("fileName", "utf8", (err, data) => {
if (err) {
throw err;
}
console.log(data.toString());
});
// Writing a file all at once
fs.writeFile("fileName", "New Content", (err) => {
if (err) throw Err;
console.log("File written successfully");
});
Auxiliary Actions
For this lesson, we would categorize auxiliary operations as tasks that check for existence of files, permissions and get stats.
If you have a logic to be based on some characteristics of a file, you can use the fs.stat to get stats about a file. It returns an object with details of the file. A few properties from the fs.stat object are stats.size that returns the size of the file in bytes; stats.mtime that returns the last modification time of the file; stats.birthtime returns the creation time of the file; stats.isFile() returns true if the file is a regular file; stats.isDirectory() returns true if the file is a directory.
To check if a file exist, you don't need any special method. Instead attempt the operation and then cater for the absence of the file in the error block. This style of exception handling is called "Easier to Ask for Forgiveness than Permission (EAFP)"
EAFP vs LBYL
LBYL (Look Before You Leap) vs EAFP (Easier to Ask for Forgiveness than Permission) are contrasting idioms with regards to error checking before code execution.
EAFP is preferred for file operations because it avoids race conditions. A race condition can occur when you check if a file exits, and then before you can perform your action, another process deletes the file. In this scenario, your program would think the action still exists and would attempt the action resulting in an error. By directly attempting the action and handling the error, you ensure the atomicity and avoid this potential issue.
LBYL is the opposite of EAFP where you check for a condition before performing the original action. E.g check if a file exist before reading its content.
Pros
- Simple to use.
- Good for small files where memory isn't a concern.
Cons
- Memory-heavy for large files (can crash the program if the file is too big).
- Slower for larger files since everything must be loaded before processing.
We'll dwell a little more on watching a file. In programming, this means monitoring a file for changes. The changes can be in 3 forms: modifications, deletions, or creations.
Why would you ever need to watch a file?
You may be wondering why would you or anyone watch a file. But taking action whenever a file changes is useful in a number of ways:
-
Auto-Reloading During Development Restarting a server or refreshing a browser when code changes (e.g., nodemon in Node.js, webpack --watch).
-
Log File Monitoring Like Tracking new entries in log file. If there is a new log, sends an alert or email.
-
Build Automation & CI/CD Triggering rebuilds when source files are modified (e.g., tsc --watch for TypeScript).
To watch a file in Node , you either use Node's built in fs.watch or external libraries like chokidar.
Open a terminal to begin. Create a new directory called filesystem and navigate into it.
bash$ mkdir filesystem
$ cd filesystem
Paste the code below. Kindly ensure the "target.txt" file exist in the root directory from which you would be running the program.
bash'use strict';
const fs = require('fs');
fs.watch('target.txt', () => console.log('File changed!'));
console.log('Now watching target.txt for changes...');
🐛🪲 For windows users: You may experience some issues when you make changes to the target.txt file:
- Multiple "file changed" logs for one change.
- It stops responding after the first change.
This bug is expected because of how fs.watch behave in this environment. On writing to the file it replaces same file.
Notice how the code above uses strict mode and require function. This is common js module unlike ES module that we've been using. The required() function pulls a module and returns it.
Learn more strict mode, const, require
We then progressed to call the fs module's watch() method, which takes a path to a file and a callback function to invoke whenever the file changes.
Read from command-line arguments
Let's make our program more advanced by taking in a file to watch as a command-line argument. This will introduce the process global object and how node deals with exceptions.
bashconst fs = require('fs')
const filename = process.argv[2];
if(!filename){
throw Error('A file to watch must be specified!')
}
fs.watch(filename, ()=> {
console.log(`File ${filename} changed!`)
})
console.log('Now watching ${filename} for changes...');
Extend our program by spawning a child process
Spawning a child is similar to opening up another command-line different from the original one used to run your node. This action is done for you by node so you can run any heavy stuff without blocking your main thread.
js"use strict";
const fs = require("fs");
const { spawn } = require("child_process");
const filename = process.argv[2];
if (!filename) {
throw Error("A file to watch must be specified");
}
fs.watch(filename, () => {
const ls = spawn("ls");
ls.stdout.pipe(process.stdout);
});
References
Footnotes
- LBYL vs EAFP Pasted on Tue, Aug 18, 2025.