The fs Module in Node.js

Get familiarized with the basic function provided by the fs module in Node.js.

When we develop a simple or complex web application, there are many instances where we need to use the filesystem input/output. We may want to read some data from a file, write some data to a file, append some data to a file, rename a file, and so on. Node.js offers us a built-in module name fs, which stands for “file system,” to solve all our problems related to filesystem input/output.

Reading a file

Node.js offers built-in methods to help read a file. The catch here is that there are two ways in which we could read a file, i.e., asynchronously and synchronously. In Node.js, an event loop helps to achieve asynchronous behavior.

  • Asynchronous file read: To read a file asynchronously, we’ll use the readFile() method that accepts the file location, encoding (optional), and a callback function. The callback function will be executed once the file read is completed. This function doesn’t return any value. The data read from the file is accessible to the callback function.

  • Synchronous file read: To read a file synchronously, we’ll use the readFileSync() method that accepts the file location and encoding (optional). This function also returns the data that has been read from the file.

Note: If the encoding parameter isn’t specified, the readFile() and readFileSync() functions return the contents of the file as a buffer object, which is a binary data representation of the file. However, if the encoding parameter is specified, the contents of the file are returned as a string. In our example, we’ll read a text file and specify the encoding to be utf-8 to get the correct string representation of our data.

Let’s now see how these two methods work in the code.

Get hands-on with 1200+ tech skills courses.