Reading and Writing Files in Node.js
File manipulation is a fundamental server-side feature and an essential skill for backend development.
File operations primarily involve reading and writing. Node.js provides built-in methods for these tasks, which you can invoke directly.
Creating Directories
Synchronous Method
javascript
const fileSystem = require('fs');
const targetDirectory = ${__dirname}/new_folder;
fileSystem.mkdirSync(targetDirectory);
Node.js has a built-in file system module named fs. You must import this module before performing any file operations.
You can use the fs.mkdirSync method to create a directory synchronously. Pass the name of the directory you want to create as the argument.
__dirname refers to the absolute path of the directory where the current script resides.
Asynchronous Method
javascript
const fs = require('fs');
const dirName = ${__dirname}/new_folder;
fs.mkdir(dirName, (creationError) => {
if (creationError) {
console.error('Failed to create directory:', creationError);
}
});
The fs.mkdir method allows you to create a directory asynchronously. The first parameter is the directory name, and the second is a callback function containing an err parameter to handle potential errors.
Deleting Files
After creating directories, the natural next step would be deleting directories. However, you must empty a directory before deleting it, so we will cover deleting files first.
Deleting files can be done using both synchronous and asynchronous methods.
Synchronous: fs.unlinkSync
javascript
const fs = require('fs');
const filePath = ${__dirname}/document.txt;
fs.unlinkSync(filePath);
By passing the file path and name to fs.unlinkSync, the specified file will be deleted.
Asynchronous: fs.unlink
javascript
const fs = require('fs');
const targetFile = ${__dirname}/document.txt;
fs.unlink(targetFile, (deleteError) => {
if (deleteError) {
console.error('Error deleting file:', deleteError);
}
});
The fs.unlink method takes two parameters: the first is the file path and name, and the second is a callback function that handles any deletion errors.
Deleting Directories
Before deleting a directory, you must clear all files inside the target directory. You can use fs.unlinkSync or fs.unlink to remove the files first.
Synchronous
javascript
const fs = require('fs');
const folderToRemove = ${__dirname}/new_folder;
fs.rmdirSync(folderToRemove);
Asynchronous
javascript
const fs = require('fs');
const dirPath = ${__dirname}/new_folder;
fs.rmdir(dirPath, (removeError) => {
if (removeError) {
console.error('Failed to remove directory:', removeError);
}
});
Similar to deleting files, deleting directories offers both synchronous and asynchronous methods. The asynchronous method accepts two parameters, where the second is a callback for error handling.
Writing Data
javascript const fs = require('fs'); const logMessage = 'Aplication started\n'; const writeOptions = { flag: 'a', // 'a' for append, 'w' for overwrite };
fs.writeFile('output.log', logMessage, writeOptions, (writeError) => { if (writeError) { console.error('Failed to write to file:', writeError); } });
The fs.writeFile method allows you to write content to a file. If the file does not exist, it will be created automatically.
fs.writeFile parameters explained:
- First parameter: The file name.
- Second parameter: The content to write.
- Third parameter: The write mode (e.g., append, overwrite).
- Fourth parameter: A callback function for error handling.
Reading Data
javascript const fs = require('fs'); fs.readFile('output.log', (readError, fileBuffer) => { if (readError) { console.error('Unable to read file:', readError); return; } // fileBuffer is a Buffer (binary), convert it to a string console.log(fileBuffer.toString()); });
You can use the fs.readFile method to read data. The first parameter is the file name, and the second is a callback function. The err parameter handles error messages, while data contains the retrieved data.
Note that the retrieved data is returned as a Buffer (binary type). You need to use the toString() method to convert it into a readable string.
Checking if a File Exists
javascript const fs = require('fs'); const isPresent = fs.existsSync('output.log'); console.log('File exists:', isPresent);
The fs.existsSync method checks weather a specific file exists. It returns true if the file exists, and false otherwise.
Summary
If you are using Node.js for backend development, reading and writing files is an inescapable topic. One of the most common applications for this is writing logs, such as collecting error logs.
While logs can also be stored in a database, not all computers have the same databases installed. However, if you write logs to a file, the contents can easily be opened on almost any other computer.