The ‘fs’ (file system) module of Node.js implements the file input/output operation. Methods in the fs module can be synchronous as well as asynchronous, but that is not something we’ll discuss here just yet.
Now when we know what is ‘fs’ and how can it help us we’ll use this theory in practice and open up a new project in Visual Studio Code.
Step 1:
1. Declaring a constant named ‘fs’ in your app.js file which will ‘require’ the ‘fs’ module for us and import it into our project.
const fs = require('fs');
2. We will use a method to create a new file in our directory and add some text to it which we will expect to be printed out later. Since we’ll be making an introduction app we’ll call our file ‘notes.txt’ as our introduction notes.
fs.writeFileSync('notes.txt', 'My name is Likii');
The fs.writeFileSync() method creates a new file if the specified file does not exist yet and takes data as the second parameter. In this case, we set it to a string as we want to display our introduction notes later.
This method accepts three parameters:
fs.writeFileSync( file, data, options )
We’ve used ‘file’ to specify a name of the file we want to create, ‘data’ to display some text but we haven’t used any ‘options’.
3. Save your files and run the application to see if it all worked or did we get any errors by typing this line into your terminal window:
node app.js
If you’ve called your main js file something else then you’d need to replace app.js with whatever you’ve chosen to name your file and press enter.
4. You should now be able to see a new file in your project directory named ‘notes.txt’, as that is what we’ve named it earlier, which contains a line of text ‘My name is Likii’.
If we wanted to add another bit of text to our introduction notes we’d use a method called fs.appendFileSync which will help us do just that.
fs.appendFileSync('notes.txt', 'I like tomato soup.');
This method will take a look at our notes.txt file and add data that we set in our second parameter to it. We should save all of our files and run our application again. When we revisit our notes.txt file we can see something like this:
My name is Likii.I like tomato soup.
Pay attention to the lack of spacing between the dot and the start of the new sentence. This method won’t automatically give you nice formatting and new lines, so it’s something to be aware of ?