Topic 004: File operation in Node.js
Here’s a detailed explanation of handling file operations using Node.js, focusing on both the built-in fs module and the fs-extra package, along with practical examples.
The fs (file system) module in Node.js provides a variety of functions to work with the file system. It supports both synchronous and asynchronous operations, but asynchronous methods are generally preferred for non-blocking I/O.
Using fs.readFile, you can read a file without blocking the event loop:
const fs = require("fs");
fs.readFile("example.txt", "utf8", (err, data) => {
if (err) {
console.error("Error reading the file:", err);
return;
}
console.log("File content:", data);
});- Parameters:
- The first parameter is the file path.
- The second parameter is the encoding (optional).
- The third parameter is a callback function that handles the file content or error.
To write data to a file, use fs.writeFile:
const fs = require("fs");
const content = "This is some example content.";
fs.writeFile("example.txt", content, "utf8", (err) => {
if (err) {
console.error("Error writing to the file:", err);
return;
}
console.log("File has been written.");
});- Parameters:
- The first parameter is the file path.
- The second parameter is the content to write.
- The third parameter is the encoding (optional).
- The fourth parameter is a callback function that handles success or error.
To append data to a file, use fs.appendFile:
const fs = require("fs");
const content = "\nAppending this text.";
fs.appendFile("example.txt", content, "utf8", (err) => {
if (err) {
console.error("Error appending to the file:", err);
return;
}
console.log("Content has been appended.");
});To delete a file, use fs.unlink:
const fs = require("fs");
fs.unlink("example.txt", (err) => {
if (err) {
console.error("Error deleting the file:", err);
return;
}
console.log("File has been deleted.");
});fs-extra is an npm package that extends the fs module with additional functionality and simplifies common tasks.
First, install the package:
npm install fs-extraCopying a File
const fs = require("fs-extra");
fs.copy("source.txt", "destination.txt")
.then(() => {
console.log("File copied successfully.");
})
.catch((err) => {
console.error("Error copying the file:", err);
});- The
copymethod is simple and handles file copying with a promise-based interface.
Ensuring a Directory Exists
const fs = require("fs-extra");
fs.ensureDir("new-dir")
.then(() => {
console.log("Directory ensured.");
})
.catch((err) => {
console.error("Error ensuring directory:", err);
});- The
ensureDirmethod creates a directory if it doesn’t exist, avoiding errors if the directory is already present.
Removing a Directory
const fs = require("fs-extra");
fs.remove("new-dir")
.then(() => {
console.log("Directory removed.");
})
.catch((err) => {
console.error("Error removing directory:", err);
});- The
removemethod is used to delete directories or files and it handles all cases, including non-empty directories.
-
fsModule:- Ideal for basic file operations like reading, writing, appending, and deleting files.
- Provides both synchronous and asynchronous methods.
- Requires handling callbacks for asynchronous operations, which can be managed using Promises or async/await.
-
fs-extraPackage:- Extends
fswith more convenient methods for common tasks. - Uses Promises, making it easier to handle asynchronous operations, especially with
async/await. - Includes methods like
copy,ensureDir, andremove, which are not available in the defaultfsmodule.
- Extends
By utilizing these tools, you can efficiently manage file operations in your Node.js applications. Whether you need simple file reads and writes or more advanced operations like ensuring directories or copying files, the fs module and fs-extra package have you covered.