As you remember, pure JavaScript has limitations because it was originally designed for browsers only. But the Node.js platform allows you to interact with the file system. In this topic, we will find out what the fs module is.
Import fs module
First, let's clarify that fs is just short for the file system. Let's take a look at importing the fs module using the CommonJS and ES6 Module syntax.
Here's the CommonJS syntax:
const fs = require('node:fs');
And here's an example of the ESM (ES6 modules) syntax:
import * as fs from 'node:fs';
In this case, we will use the synchronous and the callback APIs, although it's not the only option.
const fs = require('fs'). It will work, but it is better to use the way shown above (with node:fs). It is due to security in case of using a similar npm package name.Sync API
It might be that Node.js was specifically designed for creative people who want to have multiple options to do the same thing. You have already seen that you can import the fs module in two different ways. Now, let's look at other ways to interact with files.
The most important thing for us is reading files. Consider the following syntax:
const fs = require('node:fs');
const data = fs.readFileSync('../source.js', 'utf-8');
console.log(data);
The first argument to the readFileSync method is the path to the file that we want to read. The second parameter is optional, but we can pass information about the encoding there, as we did. As you can see, the source.js file is one level higher. Also, you should have noticed that we can read not only text files. Moreover, we can read the file where the above function is called.
'utf-8') as the second argument, then a buffer will be returned, not a string.We have considered a synchronous function, which means that while reading the file, the thread is waiting for the result of the function execution. If the file is too large, then we will have to wait for a very long time for this operation to complete.
Callback API
Let's look at another way to read the same source.js file, but this time via the asynchronous way:
const fs = require('node:fs');
const data = fs.readFile('../source.js', 'utf-8', (err, data) => {
if (err) throw err;
console.log(data);
});
The first two arguments of the method are similar to the synchronous version, but now we must use the required callback argument. In our case, we use an arrow function, in which the error is passed as the first parameter and the contents of the file as the second one.
The callback API is better than the synchronous one because subsequent synchronous operations will be performed without waiting for any large file to be read.
Conclusion
In this topic, we've looked at different options for importing and using the fs module. You've learned the pros and cons of callback and synchronous APIs and figured out how to read files using different methods.