What better way to bring in the holidays than by taking a look at Node’s File System (fs) module!
To use File System, I imported the module:
For this example, let’s say we have a JSON file named data.json with a list of Christmas movies. We want to add a new movie to the file and save it to a new file called updated.json that doesn’t exist yet.
Our data.json file looks like this:
And the object we want to add to the JSON looks like this:
First, I read the contents of the data.json file and saved it into a variable:
I used fs to access the File System module. The first argument readFile() takes is the file we want to read followed by ‘utf8’ which we add otherwise we’ll get a bunch of strange numbers that aren’t converted into characters. Since readFile() is asynchronous, I added a callback function that fires once it’s finished grabbing the data. I added in some minimal error checking, and tapped into data which holds our JSON file data. Finally, since the data read from the file comes to us a string, I converted it to JSON using JSON.parse().
Next, I pushed the new movie, A Christmas Story, into the movies array in the JSON.
When writing JSON to a file, we have to turn it into a big string, the way it came to us, otherwise the file doesn’t know what to do with the data. To do this, I used JSON.stringify() and saved it into a variable named updated:
To finish, I used fs.writeFile() which takes the file to write to and then the data you want to write. WriteFile() will create the file if it doesn’t exist.
The finished code looks like this. To run the code, go to the root of your folder and run node yourFileName. Once run, you’ll see the new updated.json file appear in the project’s root:
We only scratched the surface of fs, but as you can see, the module gives us endless possibilities for creating and adding data files in our applications.<-- Back to blog list