Let’s start by first writing data to a JSON file.
Create new JavasScript file named
index.js and include the File System (fs) module:
Next we’ll declare a
books variable that contains our JSON data:
We then need to convert the JSON object to a string:
Without converting to a string the data would be written as
Now we can write the data to a file using
Run the code using
node index.js and a new
data.json file with the JSON data should have been created alongside the
index.js file. If no file was created check the error messages that have been logged in the console to debug the problem.
Ok, now that we know how to write JSON data to a file let’s now read that data.
To read data we’ll use
fs.readFile in the
index.js file as follows:
This loops through each of the books in our JSON file and logs that data to the console:
That’s all for this tutorial. You should now have an understanding of how to use a simple JSON file to read and store data. While you’re here you may be interested in reading some of our other Node.js tutorials.