How to Write JSON File in Node.js: Simple Guide
In Node.js, you can write a JSON file by converting your JavaScript object to a JSON string using
JSON.stringify() and then saving it with fs.writeFileSync() or fs.writeFile() from the fs module. This lets you store data in a file in JSON format easily.Syntax
To write a JSON file in Node.js, you use the fs module's writeFileSync or writeFile function. First, convert your object to a JSON string with JSON.stringify(). Then pass the filename, the JSON string, and optionally the encoding and a callback (for async).
fs.writeFileSync(filename, data, encoding): writes file synchronously.fs.writeFile(filename, data, encoding, callback): writes file asynchronously.JSON.stringify(object): converts object to JSON string.
javascript
const fs = require('fs'); const data = { key: 'value' }; const jsonString = JSON.stringify(data); // Synchronous write fs.writeFileSync('file.json', jsonString, 'utf8'); // Asynchronous write fs.writeFile('file.json', jsonString, 'utf8', (err) => { if (err) throw err; console.log('File saved!'); });
Example
This example shows how to write a JavaScript object to a JSON file asynchronously. It converts the object to a JSON string and saves it to data.json. After saving, it logs a success message.
javascript
import { writeFile } from 'fs'; const user = { name: 'Alice', age: 30, city: 'Wonderland' }; const jsonData = JSON.stringify(user, null, 2); // pretty print with 2 spaces writeFile('data.json', jsonData, 'utf8', (err) => { if (err) { console.error('Error writing file:', err); return; } console.log('JSON file has been saved.'); });
Output
JSON file has been saved.
Common Pitfalls
Common mistakes when writing JSON files in Node.js include:
- Not converting the object to a JSON string before writing, which causes errors.
- Forgetting to handle errors in asynchronous writes, leading to silent failures.
- Using synchronous writes in performance-critical or server environments, which can block the event loop.
- Not specifying encoding, which can cause unexpected file content.
Always use JSON.stringify() and handle errors properly.
javascript
const fs = require('fs'); const data = { name: 'Bob' }; // Wrong: writing object directly (will cause error or write [object Object]) // fs.writeFileSync('wrong.json', data); // Right: convert to JSON string fs.writeFileSync('right.json', JSON.stringify(data), 'utf8');
Quick Reference
Summary tips for writing JSON files in Node.js:
- Use
JSON.stringify(object)to convert data. - Use
fs.writeFilefor non-blocking writes,fs.writeFileSyncfor simple scripts. - Always specify
'utf8'encoding to write text files correctly. - Handle errors in asynchronous writes to avoid silent failures.
Key Takeaways
Always convert your object to a JSON string using JSON.stringify before writing to a file.
Use fs.writeFile for asynchronous, non-blocking file writes and handle errors in the callback.
Specify 'utf8' encoding to ensure the file is saved as readable text.
Avoid synchronous writes in production to prevent blocking the Node.js event loop.
Check for errors when writing files to catch and handle issues early.