Write / add data in JSON file using Node.js
To append data to a JSON file with Node.js using fs
, do:
- Fetch your data with
fs.readFile()
- Modify the parsed object
- Secure it back with
fs.writeFile()
JSON.parse()
andJSON.stringify()
are your wingmen in JSON handling.
Checking for file existence and error handling
Because you won't jump off a cliff without checking the landing, let's verify the JSON file's existence and handle any nasty surprises that could cause data loss:
- Use
fs.stat()
to check file presence - Handle errors with
console.error
to provide contextual diagnostics
Tackling large datasets
Handling large amounts of data with a standard file system is like eating soup with a fork. When dealing with Moby Dick-size datasets, consider the database lifebuoy:
- Databases like MongoDB or SQLite can store your data maze and still offer powerful querying.
- Although a shift to a database might run you late for dinner, the benefits make it worth the extra mile.
Synchronous vs. asynchronous operations
Selecting between synchronous and asynchronous operations is like choosing between a cheeseburger and a salad; both are good, depending on your appetite and health goals:
- Synchronous file operations, using
fs.readFileSync
andfs.writeFileSync
, hold up the line until they finish. They're simpler but may slow down your script's metabolism. - Asynchronous file operations, using
fs.readFile
andfs.writeFile
, give freedom to multitask. Dressing these with promises orasync/await
can turn your script into a haute couture masterpiece.
Readable JSON for debugging
Want your JSON to be prettier than your neighbor's yard? Formatting can make your data easier to read and debug:
- Make your JSON string handsome with
null
and4
passed toJSON.stringify()
. That's one small step for data, one giant leap for readability.
Managing data updates
Use timestamped filenames or versioning mechanisms to keep track of data modifications. Because trust me, you don't want to search for a needle in a haystack.
- Naming files with current date and time will make each of them unique, like a fingerprint.
- Make sure to backup your JSON files before each data addition. Because "Oops" isn't a great data recovery plan.
Was this article helpful?