fs module
File System is an essential built-in module of Node that contains utility methods for working with files and directories.
Every method associated with fs
has a blocking and asynchronous implementation. The former obviously blocks the event queue, the latter does not.
The synchronous methods are useful to have in some contexts but in general and with real-world applications, you should be using the async implementation so as to accord with the single-threaded event-driven architecture of Node.
Common I/0 methods
Read directory
Return a string array of all files in the current directory.
fs.readdir("./", function (err, files) {
if (err) {
console.error(err);
} else {
console.log(files);
}
});
Read from file
fs.readFile("./lorem.md", "UTF-8", function (err, fileContents) {
console.log(fileContents);
});
Write to file
let md = `A new file`;
fs.writeFile("testFile.md", md.trim(), function () {
console.log("File was created");
});
Appending to file
fs.appendFile("testFile.md", "new content");
Create directory
if (!fs.existsSync("directory_name")) {
fs.mkdir("directory_name", function (err) {
if (err) {
console.err(err);
}
});
} else {
console.warn("Directory already exists");
}
Rename and remove files
fs.rename("./filename.js", "./newname.js", function () {
console.log("file renamed");
});
// Remove file
fs.unlink("./file-to-delete", function (err) {
if (err) {
console.error(err);
}
});
Rename and remove directories
// Best to use synchronous method here
fs.rmSync("/dir", { recursive: true, force: true });