File System

Learn to use the file system module in Node.js.

The fs module

fs is a built-in Node.js module that allows us to interact with the file system. It has quite a few methods, some of which have both synchronous and asynchronous variants. Before we move ahead with code examples, it should be noted that the asynchronous forms of the methods always take a completion callback as the last argument. For this callback, the first argument is reserved for an exception. This will be easier to understand once we see the code.

Reading files

The fs module provides an easy way to read files using the fs.readFile method. It is passed a file path, optional arguments, such as encoding, and a callback function that will be called with data read from the file. Let’s look at both the asynchronous and synchronous versions of this method.

Get hands-on with 1200+ tech skills courses.