To write JSON to a file in JavaScript, we can use the built-in fs
module in Node.js.
Here's an example code snippet that demonstrates how to write JSON data to a file:
index.tsx396 chars21 lines
Here, we first require the fs
module, which provides an API for interacting with the file system. Next, we define some sample JSON data that we want to write to a file.
We then convert the JSON data to a string format using the JSON.stringify
method, which serializes the data into a string format.
Finally, we use the fs.writeFile
method to write the string data to a file named data.json
. The method takes three parameters: the file name, the data to be written, and a callback function to be called once the write operation is complete. If there was an error during the write operation, we log the error to the console. Otherwise, we log a success message.
gistlibby LogSnag