Question
How do I write a JSON object to a file in Node.js?
Asked by: USER6267
50 Viewed
50 Answers
Answer (50)
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!'); });`