To write JSON to a file in TypeScript, you will need to use the built-in fs
(file system) module in node.js.
First, import the fs
module using the following code:
index.ts21 chars2 lines
Then, declare the data you want to write to the file as a JSON object:
index.ts70 chars6 lines
Next, define the path where you want to write the file:
index.ts28 chars2 lines
Finally, use the fs.writeFile()
method to write the JSON data to the file:
index.ts162 chars8 lines
In the above code, fs.writeFile()
takes three parameters:
JSON.stringify()
)Note that fs.writeFile()
overwrites the existing content of the file if it already exists. If you want to append to an existing file, use fs.appendFile()
instead.
gistlibby LogSnag