The fs Module
Explore the fs module in Node.js to learn how to load it, inspect file details, and read file contents using the Promise-based API. Understand synchronous and asynchronous file operations and practice using async/await for cleaner code in handling files.
We'll cover the following...
Overview
The fs module is a built-in global Node.js module that exposes an API for accessing, manipulating, and interacting with the file system.
We’ll use a few methods from the fs module to read and write information to test.txt.
All fs operations are available either in synchronous or asynchronous forms (click here for details).
In this chapter, we’ll use a newer feature of fs, called the fs Promises API, which returns Promise objects so that we can use the async and await keywords instead of callbacks to handle asynchronicity.
We can access the API by importing it at the top of the file via require('fs').promises.
Load the fs module
The module system uses the require() function to load in a module and access its contents.
To load in the fs module and get access to its properties and methods, we use require() at the top of the file-system.js file:
Inspect file details
Every file comes with a set of information, such as the size, creation time, and so on, that we can inspect with fs.stat. We can use the output of fs.stat() to perform common programming tasks, such as checking whether or not the path resolves to a file or a directory.
Add the following code right below the fs module require() function:
The getStats() method accepts a file path as an argument and calls the fs.stat() method using the async/await pattern. If the fs.stat() call is successful, the file stats are logged to the console. Otherwise, an error is logged.
In the nodejs-api directory, run the script using the command below:
We can call special methods on the stats object to obtain further information about the object. For example, .isFile() and .isDirectory() check whether a given file path leads to a file or a directory, respectively. To better understand how they work, modify getStats() as follows:
We’ll see isFile: true and isDirectory: false logged to the console since ./test.txt leads to a file.
When we’re done, don’t forget to comment out getStats('./test.txt') so that we can keep the console clear when testing out the remaining fs methods.
Read the contents of a file
We can read a file with fs.readFile(). This method accepts two arguments:
-It accepts a file path. -It accepts a character encoding type (for example, utf8).
Add the following code to the file-system.js file:
In the nodejs-api directory, run the script using the $ node file-system.js command.
Try it out
Follow the steps below to try it out:
- Press the “Run” button below to start the terminal, and then start the application with the following command:
-
Uncomment lines 7 and 8, and press the “Run” button.
-
Rerun the script using the command given above, and check the console’s contents now.
Note: Before executing the command, press the “Run” button again to update the application with the modified code.
-
In line 15, comment out
getStats('./test.txt'). -
In lines 17–26, comment out the
fs.readFile()method in the widget below. -
Press the Run button to save code.
-
Rerun the script using the same command, and see how the
fs.readFile()method is implemented by checking the console’s contents.
let count = 5;
// the setInterval() function invokes the callback every 1000 milliseconds
const countDown = setInterval(() => {
console.log(`counting down ${count}`);
count--;
if (count < 0) {
console.log("Time's up!");
// clears the timer when the count is negative
clearInterval(countDown);
}
}, 1000);