Introduction
JSON (JavaScript Object Notation) is a lightweight data format that is easy for humans to read and write, and easy for machines to parse and generate. Node.js provides excellent support for working with JSON data through its core fs
and path
modules.
In this in-depth tutorial, you’ll learn how to read and write JSON files in Node.js using simple yet powerful techniques. We’ll cover:
- Reading JSON files using
fs.readFileSync
andfs.readFile
- Writing JSON files with
fs.writeFileSync
andfs.writeFile
- Parsing JSON with
JSON.parse()
- Stringifying JSON with
JSON.stringify()
- Asynchronous and synchronous methods
- Solving common errors
Follow along as we tackle the essential skills for manipulating JSON data in your Node.js applications.
Read and Write JSON Files in Node.js
Reading JSON Files in Node.js
Let’s first explore how to read and parse JSON files using the Node.js fs
module.
Read JSON File Synchronously
To read a JSON file synchronously in one shot, use fs.readFileSync()
passing the file path and ‘utf8’ encoding:
const fs = require('fs');
const jsonData = fs.readFileSync('data.json', 'utf8');
const data = JSON.parse(jsonData);
This will return the raw file contents as a string. We then parse it into a JavaScript object with JSON.parse()
.
Read JSON File Asynchronously
For asynchronous reading, use fs.readFile()
and provide a callback:
fs.readFile('data.json', 'utf8', (err, jsonData) => {
if (err) throw err;
const data = JSON.parse(jsonData);
// ...
});
The callback is passed the error and file data. We handle errors, parse the JSON string, and process the resulting JavaScript object.
This non-blocking method is useful for large files or performance sensitive code.
Writing JSON Files in Node.js
Now let’s look at writing JSON data to files using fs.writeFileSync()
and fs.writeFile()
.
Write JSON File Synchronously
To synchronously write a JSON object to file, stringify it with JSON.stringify()
and write using fs.writeFileSync()
:
const fs = require('fs');
const data = { hello: 'world' };
const jsonData = JSON.stringify(data);
fs.writeFileSync('data.json', jsonData);
This will overwrite the file if it already exists.
Write JSON File Asynchronously
For asynchronous writing, use fs.writeFile()
and pass the callback:
const jsonData = JSON.stringify(data);
fs.writeFile('data.json', jsonData, err => {
if (err) throw err;
console.log('File saved!');
});
We check for errors in the callback and log a success message when complete.
This is useful for non-blocking writes or fallible code paths.
Handling Errors
When working with JSON data, you may encounter errors like:
- Invalid JSON syntax causing
JSON.parse()
to fail - Filesystem errors from
fs
module methods - Encoding problems from non-UTF8 files
- Path resolution issues
Robustly handle errors at each step:
try {
const jsonData = fs.readFileSync('data.json', 'utf8');
const data = JSON.parse(jsonData);
} catch (err) {
// Handle errors
if (err.code === 'ENOENT') {
// Handle file not found
} else if (err instanceof SyntaxError) {
// Handle invalid JSON
} else {
throw err;
}
}
This ensures your application gracefully handles edge cases when working with JSON and filesystem methods.
In Summary
Reading and writing JSON files is seamless in Node.js with the fs
and path
modules. Key takeaways include:
- Use
fs.readFileSync()
andfs.readFile()
to read JSON files - Leverage
fs.writeFileSync()
andfs.writeFile()
to write JSON - Parse JSON strings to JavaScript objects with
JSON.parse()
- Stringify JavaScript objects into JSON with
JSON.stringify()
- Handle errors appropriately at each stage
With these fundamentals, you can easily persist and process JSON data in your Node.js apps. The JSON format strikes an excellent balance between human readability and machine parsability.
Frequently Asked Questions
Here are some common questions about reading and writing JSON files in Node.js:
Q: How do you parse a JSON file in Node.js?
A: Use JSON.parse()
and pass the JSON string loaded from file. This returns a JavaScript object.
Q: What is the difference between synchronous and asynchronous file methods in Node.js?
A: Synchronous methods like fs.readFileSync()
block execution until complete. Asynchronous methods like fs.readFile()
use callbacks and are non-blocking.
Q: How can you write an async/await wrapper for fs.readFile()?
A: Use a helper function that returns a Promise and call fs.readFile() inside. Then await the returned Promise.
Q: Should you use JSON.stringify() before writing JSON data to file?
A: Yes, use JSON.stringify()
to ensure the JavaScript object is serialized into valid JSON for writing.
Q: How can you handle errors when reading/writing JSON files in Node.js?
A: Wrap the operations in try/catch blocks and handle specific errors like invalid JSON syntax, encoding issues, etc.