To create a JSON file in JavaScript, you can use the fs
(file system) module built into Node.js. Here's an example code snippet that demonstrates how to do this:
257 chars15 lines
In this code:
fs
module to gain access to file system functionsdata
that we want to store as JSONdata
object to a JSON string using JSON.stringify
data.json
using fs.writeFile
The second argument to JSON.stringify
is a "replacer" function to transform values and properties before serialization. In this case, we don't need any replace, so we pass null
. The third argument is the number of spaces to use for indentation in the output JSON. Here we use 2
to make the file more readable.
When fs.writeFile
is called, it writes the jsonData
string to a file named 'data.json'. If there are no errors, it logs 'Data written to file' to the console.
gistlibby LogSnag