append to a json file in typescript

index.ts
import fs from 'fs';

const data = {name: 'John', age: 25};

fs.readFile('./data.json', 'utf-8', (err, jsonString) => {
  if (err) {
    console.log(`Error reading file from disk: ${err}`);
    return;
  }
  try {
    const jsonObject = JSON.parse(jsonString);
    jsonObject.push(data);
    fs.writeFile('./data.json', JSON.stringify(jsonObject), 'utf-8', (err) => {
      if (err) {
        console.log(`Error writing file: ${err}`);
      } else {
        console.log(`Data added to file`);
      }
    });
  } catch (err) {
    console.log(`Error parsing JSON string: ${err}`);
  }
});
590 chars
24 lines

Explanation:

  • fs module is imported to access file system functions.
  • The data object to be appended is defined.
  • The fs.readFile() function is used to read data.json file.
  • In the callback function of fs.readFile():
    • if block checks for errors while reading the file.
    • try block is used to parse the JSON string and add the data object to it.
    • fs.writeFile() function is called to write the updated JSON string to the file.
    • In the callback function of fs.writeFile(), if block checks for errors while writing the file.

gistlibby LogSnag