A Deep Dive into Node.js’s File System “fs” Module
📂🚀
Well, as a developer we always are fascinated by an idea of creating new files on the disk programmatically and doing many other operations on that file and data inside it. In short we can call it playing with files ▶📂
Today we will be learning, how we can
- Create new files and directories 📁✔
- Adding data to a newer file or appending data to the existing file ✍📁
- Reading Data from Files 📖📁
- Watching Files for Changes 🔎📁
- Copying Files and Overwriting Files ©📁
- Deleting Files ❌📁
Getting Started
In order to play around with the file system we will be needing the “fs” module from the node library. In order to get this module you can use the following command:
const fs = require("fs");
Now, we are ready to play around with the files.
Creating a new File:
We do have two options to create a file:
i) we can create an empty file without adding any initial data to it, or
ii) we can create a file, and also add some initial data to it while its creation
If you want to create a new empty file without adding any data to it, you can use the fs
module's openSync()
method (synchronous) or open()
method (asynchronous) to create a new file descriptor, and then use the closeSync()
method (synchronous) or close()
method (asynchronous) to close it.
Here’s an example of using the openSync()
method to create a new empty file called notes.txt
:
const fs = require("fs")
const fileDescriptor = fs.openSync("notes.txt", "w");
fs.closeSync(fileDescriptor);
console.log("File Created Successfully")
This will create a new file with a name notes.txt.
The openSync()
method takes two arguments, the first one is the path to the file and the second one is the flag that tells the method to open the file for writing. The open()
method takes a callback function as the third argument that will be called after the file is created.
It is important to note that the openSync()
method creates a file descriptor that must be closed with the closeSync()
method, and the open()
method creates a file descriptor that must be closed with the close()
method.
Also, if you want to create the file in a specific directory, you can provide the full path to the file as the first argument.
Writing Data to a new file or creating a new one is also an option. The fs
module in Node.js already has a method called writeFileSync()
that allows you to write data to a file in synchronous mode. Here's an example of how you can use it to write some text to a file called notes.txt
:
const fs = require("fs");
fs.writeFileSync("notes.txt", "Some text added to this file.");
console.log("File written.");
This code will create a new file called notes.txt
in the current directory and write the specified text to it. If the file already exists, it will be overwritten with the new data.
The writeFileSync()
method takes two arguments: the first one is the path to the file, and the second one is the data you want to write to the file. It can be a string, a buffer, or a typed array.
It is important to note that writeFileSync()
writes data to a file in synchronous mode, this means that the program will wait until the file is written before moving on to the next line of code.
Also, you can provide the full path to the file as the first argument if you want to create the file in a specific directory.
Well, so far we have seen that writeFileSync()
actually overwrites the existing content of the file. How about appending more text to this file?
To append more text to the same file, you can use the fs.appendFileSync()
method. This method works similarly to fs.writeFileSync()
, but instead of overwriting the entire file, it appends the new text to the end of the file.
Here’s an example of how you can use fs.appendFileSync()
to add more text to the notes.txt file:
fs.appendFileSync("notes.txt", "Additional text added to the file.");
Reading data from the file? To read the text from a file, you can use the fs.readFileSync()
method. This method takes the file path as its first argument, and an optional options object as the second argument. The options object can be used to specify the encoding of the file.
Here’s an example of how you can use fs.readFileSync()
to read the text from the notes.txt file:
const data = fs.readFileSync("notes.txt", { encoding: "utf8" });
console.log(data);
This will print the data to the console :)
Renaming a File? The fs
module in Node.js has a method called renameSync()
that allows you to rename or move a file in synchronous mode. Here's an example of how you can use it to rename a file called notes.txt
to mynotes.txt
:
const fs = require("fs");
fs.renameSync("notes.txt", "mynotes.txt");
console.log("File renamed.");
This code will rename the file called notes.txt
to mynotes.txt
in the current directory.
The renameSync()
method takes two arguments: the first one is the current path of the file, and the second one is the new path for the file.
It is important to note that renameSync()
renames a file in synchronous mode, this means that the program will wait until the file is renamed before moving on to the next line of code.
Also, you can use renameSync()
to move a file from one directory to another by providing the full path of the current file and the full path of the new location as the first and second argument.
It is worth mentioning that if the destination file name already exist, the previous file will be overwritten by the new one.
Deleting File!
The fs
module in Node.js has a method called unlinkSync()
that allows you to delete a file in synchronous mode. Here's an example of how you can use it to delete a file called notes.txt
:
const fs = require("fs");
fs.unlinkSync("notes.txt");
console.log("File deleted.");
This code will delete the file called notes.txt
in the current directory.
The unlinkSync()
method takes one argument which is the path of the file that you want to delete.
It is important to note that unlinkSync()
deletes a file in synchronous mode, this means that the program will wait until the file is deleted before moving on to the next line of code.
Also, you can use unlinkSync()
to delete files in any directory by providing the full path of the file as the argument. It is worth mentioning that if the file does not exist, the method will throw an error, so you should make sure that the file exists before calling the method.
Want to make a Directory?
The fs
module in Node.js has a method called mkdirSync()
that allows you to create a new directory in synchronous mode. Here's an example of how you can use it to create a new directory called mynotes
:
const fs = require("fs");
fs.mkdirSync("mynotes");
console.log("Directory created.");
This code will create a new directory called mynotes
in the current directory.
The mkdirSync()
method takes one argument which is the name of the new directory that you want to create.
It is important to note that mkdirSync()
creates a directory in synchronous mode, this means that the program will wait until the directory is created before moving on to the next line of code.
Also, you can use mkdirSync()
to create directories in any directory by providing the full path of the directory as the argument.
It is worth mentioning that if the directory already exist, the method will throw an error, so you should make sure that the directory does not exist before calling the method.
Reading Directory!
The fs
module in Node.js has a method called readdirSync()
that allows you to read the contents of a directory in synchronous mode. Here's an example of how you can use it to read the contents of a directory called mynotes
:
const fs = require("fs");
let files = fs.readdirSync("mynotes");
console.log(files);
This code will read the contents of the directory called mynotes
in the current directory and return an array of file names and directory names.
The readdirSync()
method takes one argument which is the path of the directory that you want to read.
It is important to note that readdirSync()
read the contents of a directory in synchronous mode, this means that the program will wait until the contents of the directory are read before moving on to the next line of code.
Also, you can use readdirSync()
to read the contents of any directory by providing the full path of the directory as the argument.
It is worth mentioning that if the directory does not exist, the method will throw an error, so you should make sure that the directory exist before calling the method.
Watching a File for Changes?
The fs
module in Node.js has a method called watchFile()
that allows you to monitor a file for changes in an asynchronous mode. Here's an example of how you can use it to monitor a file called notes.txt
:
const fs = require("fs");
fs.watchFile("notes.txt", (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
This code will monitor the file called notes.txt
in the current directory, and whenever the file is modified, it will log the current and previous modification time of the file.
The watchFile()
method takes two arguments, the first argument is the path of the file that you want to monitor and the second is a callback function that will be called when the file is modified.
The callback function will be called with two arguments, the first is the current status of the file and the second is the previous status of the file, both are objects that contains information about the file such as the last modification time, size and etc.
It is important to note that watchFile()
monitors a file in asynchronous mode, this means that the program will not wait for the callback function to complete before moving on to the next line of code.
Also, you can use watchFile()
to monitor files in any directory by providing the full path of the file as the argument.
It is worth mentioning that if the file does not exist, the method will throw an error, so you should make sure that the file exists before calling the method. Also, If you don’t need to monitor file anymore, you can use fs.unwatchFile()
method to stop monitoring the file.
Copying a File from one Location to Another
The fs
module in Node.js has a method called copyFileSync()
that allows you to copy a file from one location to another in synchronous mode. Here's an example of how you can use it to copy a file called notes.txt
from a directory called mynotes
to a directory called backup
:
const fs = require("fs");
fs.copyFileSync("mynotes/notes.txt", "backup/notes.txt");
This code will copy the file called notes.txt
from the directory called mynotes
to the directory called backup
.
The copyFileSync()
method takes two arguments, the first argument is the path of the file that you want to copy and the second is the path of the location where you want to copy the file to.
It is important to note that copyFileSync()
copy file in synchronous mode, this means that the program will wait until the file is copied before moving on to the next line of code.
Also, you can use copyFileSync()
to copy files from any directory to any other directory by providing the full paths of the files.
It is worth mentioning that if the source file does not exist, the method will throw an error, so you should make sure that the file exists before calling the method. Also, if the destination file already exists, it will be overwritten by the source file.
Well, you deserve claps 👏 if you read and tried the commands and methods mentioned in the file above. It’s fun, right? 🤩