write json to a file in typescript

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.ts
import fs from 'fs';
21 chars
2 lines

Then, declare the data you want to write to the file as a JSON object:

index.ts
const data = {
    name: 'John',
    age: 30,
    city: 'New York'
};
70 chars
6 lines

Next, define the path where you want to write the file:

index.ts
const path = './data.json';
28 chars
2 lines

Finally, use the fs.writeFile() method to write the JSON data to the file:

index.ts
fs.writeFile(path, JSON.stringify(data), (err) => {
    if (err) {
        console.error(err);
        return;
    }
    console.log('Data written to file');
});
162 chars
8 lines

In the above code, fs.writeFile() takes three parameters:

  • The file path
  • The JSON data (converted to a string using JSON.stringify())
  • A callback function that is called when the write operation is complete. If an error occurs during the write operation, the error object will be passed to this function.

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