So far, we’ve learnt developing nodejs API with GET and POST request in json format. Today, let’s raise our learning bar and learn saving or writing the json data to a file.
Since, nodejs has huge repository of node modules, it makes our life pretty easy to do almost anything just by importing the respective module.
For instance, in this post, we are going to save the json data to a file for which we need a file stream library that enables us to read and write the data. With nodejs, it is just simple to accomplish this. All you need to do is, install the ‘fs’ module using npm(Node Package Manager) using following command in terminal:
Let’s first add the user data which includes the user name, profession and password. Since, we require the user’s input here, let’s use POST request to send these parameters.
Here, I am saving the data to a file named users.json
Now let’s run the server to save the user data:
Example app listening at http://localhost:8081
To insert the data, send a POST request, you may send the data through form-data or use third party REST client apps like REST client, Http Request or Post Master.
I have used a HTML form to add the user
Here’s the HTML code :
Here the data is inserted to users.json file now. To fetch the data from file, we use GET request.
Enter the url “http://localhost:8081/listUser” in your browser and it lists the users in the file.
That’s it! Hope this was of help. Happy coding!