The FS Module (Node v8)

What is FS?

Alex Moline
2 min readJan 31, 2021

The fs module is shorthand for the file system module which handles different input/output operations. The different methods determine whether the operation is interpreted as an input such as fs.readFile, or output like fs.writeFile, both of which will be discussed later.

For starters, a vital part of the fs module is its functionality, being both synchronous and asynchronous. Synchronous code is code that executes its operations as long as resources are available, this means that if a program is running and resources are needed for a part of it, that specific code won’t run into the necessary resources become available. Asynchronous code is the opposite of synchronous and runs regardless of resource availability. The diagram below explains the difference between the two.

The fs module denotes which methods are asynchronous or synchronous by adding sync to the method name an example being fs.readFile being asynchronous and fs.readFileSync being synchronous.

How to use the fs module?

To have access to the fs module, it is important to use the require function to have access to the file system, and its methods. Once that is done then you will have access to the methods of which we will go over two, readFile and writeFile, both having asynchronous functionality.

ReadFile, the first method is a very reliable method that reads the content of a file and can be used in a plethora of ways. The method takes in 3 parameters, the first being the path or rather the file you want to be read. The second parameter is the options of which there are two, either objects or strings. The last parameter is the callback, which contains the parameters of err- short for error, and data which is the contents of the file.

Example of readFile

Lastly is writeFile which writes data to a file. The parameters for it are the file that you want to write, the data that you want written, and options parameter like readFile, and lastly a callback with an error parameter. A unique feature with writeFile is that it replaces the file if it already exists.

Example of writeFile

In conclusion, the fs module is an important system in regards to how programmers can interact through different files in a very simplistic way.

--

--