Let's first discuss the synchronous and asynchronous forms of file system operations.
All the file system operations in Node.js follow synchronous as well as asynchronous forms.
The asynchronous form takes a completion callback as its last argument, which is invoked when the asynchronous file operation finishes its operation. The first argument of this completion callback is reserved for the exception, which is assigned the value null or undefined when the file operation is successful.
The synchronous form is written inside the try-catch block, and if an error or exception occurs, it will be handled by the catch-block.
In the last video, you learnt that the fs module need not be installed; rather, it just needs to be imported using the require function. The following statement can be used for this purpose:
const fs = require('fs');
The code that you looked at in the video is as follows:
const fs = require('fs'); const data = 'Hello students! Let\'s learn Node.js'; const options = { encoding: 'utf8', flag: 'w' } fs.writeFile('data.txt', data, options, (err) => { if (err) throw err; console.log('The file has been saved!'); });
Output:
The file has been saved!
Content written to data.txt file:
Hello students! Let's learn Node.js
You also saw that if the file data.txt does not exist, it is first created, and then, the specified text inside the data variable is added to it.
Now, let's see what happens when the writeFile API is called when the file is already created and it initially has some text inside it.
So you saw that in the case of a file that has already been created, the contents inside it are deleted and the new contents are added to it. This happened because you had specified the flag as 'w' which means write to the file.
You can read more about file system flags from this link.
Let's now discuss the synchronous form of the file operation. For this, you have an API named writeFileSync. Let's start learning about it.
The code that you looked at in the video is as follows:
const fs = require('fs'); const data = 'Hey there! I am learning Node.js'; const options = { encoding: 'utf8', flag: 'w' } try { fs.writeFileSync('data.txt', data, options); } catch(err) { throw err; }
Output:
Content written to data.txt file:
Hey there! I am learning Node.js