Node.js provides a module called fs (file system) that allows us to interact with the server’s file system.
This module gives us all the functions we need to perform operations such as reading, writing, modifying, and deleting files and directories.
When reading and writing files, it is important to specify the correct encoding. For example, utf8. If we work with binary files, such as images or compressed files, we must omit the encoding to get the data unmodified.
For large files, it is recommended to use Node.js’s streams module instead of loading all the content into memory. We will see this in the next article How to work with streams
Functions of the FS Module
Let’s look at some of the most important functions of the fs module, along with practical examples of how to use them.
Check if a file exists
The first task we often need to perform is to check for the existence of a file. For this, we use the access function, which allows us to check if a file exists and if we have permissions to access it.
import { access } from 'node:fs';
access('file.txt', (err) => {
if (err) {
console.error('The file does not exist');
return;
}
console.log('The file exists');
});
Copy a file
To make a copy of an existing file we use the copyFile function, which takes the source filename and the destination filename as parameters.
import { copyFile } from 'node:fs';
copyFile('source.txt', 'destination.txt', (err) => {
if (err) throw err;
console.log('File copied successfully');
});
Move a file
To rename or change the location of a file, we use the rename function. This allows us to move a file from one location to another or simply change its name.
import { rename } from 'node:fs';
rename('old.txt', 'new.txt', (err) => {
if (err) throw err;
console.log('File moved successfully');
});
Delete a file
To delete a file programmatically we use the unlink function, which allows us to remove a file from the file system.
import { unlink } from 'node:fs';
unlink('file.txt', (err) => {
if (err) throw err;
console.log('File deleted successfully');
});
Reading a text file
Suppose we have a file called data.txt with the following content:
This is a sample file.
It contains some lines of text.
The following code in Node.js will allow us to read this file:
import { readFile } from 'node:fs';
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
console.log('File content:');
console.log(data);
});
In this example, fs.readFile() takes three arguments: the filename (data.txt), the encoding (utf8 for text), and a callback function that executes once the reading is complete. If the reading is successful, the file content is printed to the console.
Reading a binary file
Suppose we have a file called data.txt but as binary, its bytes.
import { readFile } from 'node:fs';
fs.readFile('data.txt',(err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
console.log('File content:');
console.log(data);
});
Add a line to a file
To add content to an existing file, such as adding a new line, we use the appendFile function.
import { appendFile } from 'node:fs';
const newLine = 'New line to add';
appendFile('file.txt', `${newLine}\n`, (err) => {
if (err) throw err;
console.log('Line added to the file');
});
Create a new file and write to it
To create a new file and write content to it, we use the writeFile function.
import { writeFile } from 'node:fs';
const content = 'Content of the new file';
writeFile('new.txt', content, (err) => {
if (err) throw err;
console.log('New file created and content written');
});
Download the code
All the code from this post is available for download on Github
