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.
fs ModuleThe 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);
});
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.");
});
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 Packagefs-extra is an npm package that extends the fs module with additional functionality and simplifies common tasks.
fs-extraFirst, install the package:
npm install fs-extra
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);
});
copy method 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);
});
ensureDir method 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);
});
remove method is used to delete directories or files and it handles all cases, including non-empty directories.fs Module:
fs-extra Package:
fs with more convenient methods for common tasks.async/await.copy, ensureDir, and remove, which are not available in the default fs module.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.