write to a json file in typescript

To write to a JSON file in TypeScript, you first need to import the built-in fs (file system) module of Node.js. Then, you can use the writeFile() method of this module to write to a JSON file.

Here's some example code to write to a JSON file in TypeScript:

index.ts
import * as fs from 'fs';

// define the data you want to write to the file
const data = {
  name: 'John Doe',
  age: 30,
  email: 'johndoe@email.com',
};

// convert the data to a JSON string
const jsonData = JSON.stringify(data);

// specify the file path and name
const filePath = 'path/to/file.json';

// write the data to the file
fs.writeFile(filePath, jsonData, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.log('Data written to file successfully!');
  }
});
497 chars
24 lines

In this example, the fs.writeFile() method takes three arguments:

  1. The file path and name where you want to write the data.
  2. The data you want to write, which is a JSON string created using JSON.stringify().
  3. A callback function that is called once the data is written. This function handles any errors that occur during the write process, and prints a message to the console indicating whether the write was successful.

Note that the path specified in filePath should be relative to the current working directory of your Node.js application.

gistlibby LogSnag