Learn how to save a JSON object to a file in Node.js and retrieve it later.
Storing data in the filesystem can be a reliable approach for Node.js applications. If you have an object that can be serialized to JSON, you can follow these steps to save it to a file:
const fs = require('fs');
const storeData = (data, path) => {
try {
fs.writeFileSync(path, JSON.stringify(data));
} catch (err) {
console.error(err);
}
};
To retrieve the data from the file, you can use the fs.readFileSync()
method:
const loadData = (path) => {
try {
return fs.readFileSync(path, 'utf8');
} catch (err) {
console.error(err);
return false;
}
};
In the example above, we used the synchronous versions of the file system methods for simplicity. However, you can also use the asynchronous versions (fs.writeFile
and fs.readFile
). If you are interested in learning more about writing and reading files in Node.js, check out our guides on how to write files using Node.js and how to read files using Node.js.