Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
Sometimes the best way to store some data in a Node.js application is to save it to the filesystem.
If you have an object that can be serialized to JSON, you can use the JSON.stringify() method and the fs method fs.writeFileSync() which synchronously writes a piece of data 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, you can use fs.readFileSync():
const loadData = (path) => {
try {
return fs.readFileSync(path, 'utf8')
} catch (err) {
console.error(err)
return false
}
}
The synchronous API makes it easy to return the data directly.
For asynchronous versions, use fs.writeFile and fs.readFile. See how to write files using Node.js and how to read files using Node.js for the async APIs.