In our computer, data is organized and accessed through a file system. The Node.js file system module allows us to interact with the file system.
fs
handles file system operations such as reading to and writing from files. There are synchronous and asynchronous methods in the library.
To include the File System module, we can use the require() method:
const fs = require("fs");
Some of the methods include:
To read the content of a file using NodeJS, we can use the readFile()
and readFileSync()
methods.
The fs.readFile()
method allows us to read the content of a file asynchronously, so the execution of JavaScript code will continue down the line without waiting for the method to finish.
It takes three parameters:
const fs = require("fs");
fs.readFile("./docs/blog.txt", "utf8", (err, data) => {
if (err) throw err;
console.log(data);
});
// Hello world
Note: If we don’t add utf8, when we run the file, it will return a buffer, which is a data package.
To see our string data in text format, we can use the toString()
method:
const fs = require("fs");
fs.readFile("./docs/blog.txt", (err, data) => {
if (err) throw err;
console.log(data.toString());
});
// Result: Hello world
The readFileSync()
method reads the content of a file synchronously, so the JavaScript code execution will be stopped until the method is finished.
It has two parameters:
const fs = require("fs");
const data = fs.readFileSync("./docs/blog.txt", "utf8");
console.log(data);
We use the fs.writeFile()
method to write a file. It takes three arguments:
For example, we’d like to replace “Hello world” with “Hello there”:
const fs = require("fs");
fs.writeFile("./docs/blog.txt", "Hello there", () => {
console.log("file was changed");
});
// Result: file was changed
The fs.writeFile()
asynchronously writes data to the file, replacing it if it already exists. If the file does not exist, a new file will be created.
For example, if we run the following code, we’ll see blog2.txt
appears in our folder.
const fs = require("fs");
fs.writeFile("./docs/blog2.txt", "Hello there", () => {
console.log("file was changed");
});
// Result: file was changed
Because fs.writeFile() overwrite data, if we want to add more to a file, we need to use fs.appendFile()
.
const fs = require("fs");
const path = require("path");
// Create and write to file
fs.writeFile("./docs/blog.txt", "Hello World!", (err) => {
if (err) throw err;
console.log("Writing file ...");
// File append
fs.appendFile("./docs/blog.txt", "Learning Nodejs", (err) => {
if (err) throw err;
console.log("Appending file ...");
});
});
We use fs.rename()
to rename a file. It takes two arguments:
// Rename file
fs.rename("./docs/blog.txt", "./docs/newblog.txt", (err) => {
if (err) throw err;
console.log("File renamed...");
});
We use the fs.unlink()
method to delete a file. It takes two arguments:
const fs = require("fs");
fs.unlink("./docs/blog2.txt", (err) => {
if (err) {
console.log(err);
}
console.log("file deleted");
});
// Result: file deleted
We can check whether a file or a directory exists before deleting it with the fs.existsSync()
method.
const fs = require("fs");
if (fs.existsSync("./docs/blog2.txt")) {
fs.unlink("./docs/blog2.txt", (err) => {
if (err) {
console.log(err);
}
console.log("file deleted");
});
}
To create a new folder, we can use the fs.mkdir()
method. We’ll need to specify what folder to make and where.
const fs = require("fs");
fs.mkdir("./images", (err) => {
if (err) {
console.log(err);
}
console.log("folder created");
});
We can check whether a folder exists before creating it with the fs.existsSync()
method.
const fs = require("fs");
if (!fs.existsSync("./images")) {
fs.mkdir("./images", (err) => {
if (err) throw err;
console.log("folder created");
});
}
const fs = require("fs");
fs.rmdir("./images", (err) => {
if (err) {
console.log(err);
}
console.log("folder deleted");
});
Resources: Check fs Documentation for more methods.
A large file can take a long time to read, so we’ll waste time waiting. To avoid that, we can use Streams.
Using stream, we can start using the data before it has finished loading.
To open a file as a readable stream, we can use fs.createReadStream()
. It takes two arguments:
{ encoding: "utf8" }
so the stream will be in a readable format.We’ll then create an event listener whenever we create a chunk of data:
const fs = require("fs");
const readStream = fs.createReadStream("./docs/blog3.txt", {
encoding: "utf8",
});
readStream.on("data", (chunk) => {
console.log("--New Chunk--");
console.log(chunk);
});
We can use fs.createReadStream()
to write data to a file a bit at a time.
For example, we’ll pass data of blog3 to blog4:
const fs = require("fs");
const readStream = fs.createReadStream("./docs/blog3.txt", {
encoding: "utf8",
});
const writeStream = fs.createWriteStream("./docs/blog4.txt");
readStream.on("data", (chunk) => {
writeStream.write(chunk);
});
Using pipe, we can pass data from a readable to a writable stream in a much shorter way.
const fs = require("fs");
const readStream = fs.createReadStream("./docs/blog3.txt", {
encoding: "utf8",
});
const writeStream = fs.createWriteStream("./docs/blog4.txt");
readStream.pipe(writeStream);