To write a JSON object to a file in JavaScript, you can use the fs (file system
) module (Node.js built-in module). Here is a sample code block that writes a JSON object to a file:
index.tsx255 chars15 lines
In the above code, we are first requiring the fs
module. We then define a JavaScript object (data
).
Next, we use the JSON.stringify()
method to convert our data
object to a JSON string (jsonData
).
We use the fs.writeFile()
method to write the jsonData
to a file named data.json
. The first argument of the writeFile()
method specifies the file name and location you want to write to. The second argument is the data you want to write to the file. The third argument is a callback function that will be executed when the writeFile()
operation is complete.
If there is any error, it will throw an error, and if successful, it will log a message that the JSON data is saved to the file.
gistlibby LogSnag