Using JSON files in your Node.js application can be a useful way to persist data. For example, if you want to store data between a Node server restart, JSON files are a convenient option. Node has some built-in utilities to read and write JSON files.
Interacting with files
Files can be accessed in Node.js with the native module fs
to watch, read and write files. For a fresher on the fs module, have a look at this article Node file system. FS is a native module, and can be required without installing it. Simply call const fs = require('fs')
. You have synchronous and asynchronous versions for some provided functions. The synchronous version blocks execution of other code until they are done interacting (read, write) with the filesystem. An async function will run without blocking other code. Synchronous function have some use cases, like loading configs on startup, besides these use cases and in general async versions should be used.
To read and write files async the native fs module provides the functions fs.readFile
and fs.writeFile
.
Read a JSON file
The simplest way to read a JSON file is to require it, like so:
const jsonFile = require('./config.json');
There are some things to consider, when using this approach. The file will be only read once, and it will be cached. This means, when requiring it again, the cached version will be returned. This is fine for static data, but not for data that changes dynamically. For dynamic data we have to use fs.readFile
.
Read a JSON file with fs.readFile
Let's say we have a json file of a customer, and we want to print the customer address. We would have to read the JSON data from the file and then parse it to a JavaScript object.
customer.json:
"firstName": "Mario",
"address": "Null Island",
"email": "hello@mario.com"
To read the file we have to provide the relative file path, format (optional), and a callback function to fs.readFile
.
const fs = require('fs');
fs.readFile('./customer.json', 'utf8', (err, data) => {
if (err) {
console.log('File read failed:', err);
return;
}
console.log('File data:', data);
});
Now we have the contents of the file as a JSON string. We can parse the JSON string with the global helper method JSON.parse()
. If parsing the JSON throws an error, we have to handle it in a catch
block.
const fs = require('fs');
fs.readFile('./customer.json', 'utf8', (err, data) => {
if (err) {
console.log('Error reading file:', err);
return;
}
try {
const customer = JSON.parse(data);
console.log('Customer address is:', customer.address);
} catch (err) {
console.log('Error parsing JSON:', err);
}
});
Now we have an object representation of the data in the JSON file. We can also read the data synchronously with fs.readFilySync
.fs.readFileSync
does not take a callback function and returns the data direct after reading the file. Though it blocks all other code.
Write to a JSON file with fs.writeFile
Writing is similar to reading a JSON file, the async function fs.writeFile
writes data to the file system.
Let's say we want to write a JavaScript object to a JSON file. Similar to parsing data into an object when reading, we have to transform data into a string to be able to write it to a file. We have to create a JSON string of the javascript object with the global helper method JSON.stringify
. This JSON string representation of a JavaScript object then can be written to a file.
We have to create a data object and turn it into a string.
const customer = {
firstName: 'Mario',
address: 'Null Island',
email: 'hello@mario.com',
};
const jsonString = JSON.stringify(customer);
Once the data is stringified, we can write it to a file with fs.writeFile
.
const fs = require('fs');
const customer = {
firstName: 'Mario',
address: 'Null Island',
email: 'hello@mario.com',
};
const jsonString = JSON.stringify(customer);
fs.writeFile('./newCustomer.json', jsonString, err => {
if (err) {
console.log('Error writing file', err);
} else {
console.log('Successfully wrote file');
}
});
That’s it! Once the callback runs, the file has been written to disk. Files can also be written synchronously with fs.writeFileSync
.
JSON is one of the most common types of data you’ll work with in Node, and being able to read and write JSON files is very useful. You’ve learned how to use fs.readFile and fs.writeFile to asynchronously work with the filesystem, as well as how to parse data to and from JSON format, and catch errors from JSON.parse.
TL;DR
- Use
fs.readFile
to read files async - Use
fs.writeFile
to write files async - Use async methods to avoid code execution blocking.
Thanks for reading and if you have any questions , use the comment function or send me a message @mariokandut.
If you want to know more about Node, have a look at these Node Tutorials.
💰: $100 (credits) for you to start your cloud journey with DigitalOcean!
Top comments (1)
Great post!!