How do I write a JSON object to a file in Node.js?

Question

Grade: Education Subject: Support
How do I write a JSON object to a file in Node.js?
Asked by:
50 Viewed 50 Answers

Answer (50)

Best Answer
(301)
Use `JSON.stringify()` to convert the JSON object into a string, then write the string to the file using `fs.writeFile()`. Example: `const data = { name: 'John', age: 30 }; fs.writeFile('myFile.json', JSON.stringify(data), (err) => { if (err) throw err; console.log('File written successfully!'); });`