read a json file in typescript

To read a JSON file in TypeScript, we need to use the fs (filesystem) module that provides us with a way to interact with the file system. Here is an example code snippet to read a JSON file in TypeScript:

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

// Define the path to the JSON file
const path: string = 'path/to/file.json';

// Read the JSON file
fs.readFile(path, 'utf8', (err: NodeJS.ErrnoException | null, data: string) => {
  if (err) {
    console.error(err);
    return;
  }

  // Parse the JSON string to JSON object
  const jsonObj: any = JSON.parse(data);

  console.log(jsonObj);
});
375 chars
18 lines

In this code, we import the fs module, define the path to the JSON file, and use the readFile method to read the file asynchronously. Inside the callback function, we handle any errors that may occur and parse the JSON string to a JavaScript object using JSON.parse() method.

Note that due to the asynchronous nature of the readFile method, we need to use a callback function to handle the result of the file read.

related categories

gistlibby LogSnag