parsing a JSON file w/ TypeScript

Note to my future self re: parsing a JSON file

I want to read a JSON file in a node project with TypeScript (via ts-node).

I basically want this:

const data = readFileSync(path)
const res = JSON.parse(data)

But to get it working:

  1. you'll need to import readFileSync. you can then use import statements instead of require, but in either case:

  2. you'll probably want to install @types/node as a dev dependency to get your linter to be happy.

  3. you'll also need to cast the data to a string. Otherwise you'll get: 2345: Argument of type 'Buffer' is not assignable to parameter of type 'string'.

The return type of fs.readFileSync is string | Buffer. (Buffer being Node's way of representing [a sequence of bytes])https://nodejs.org/dist/latest-v14.x/docs/api/buffer.html#buffer_buffer I'm not sure how node determines which it's going to yield. maybe it's based on file size?)

So the whole thing is:

import { readFileSync } from 'fs';

const data = readFileSync(path)
const res = JSON.parse(data.toString())

by the way

Here's the list of TypeScript compiler errors. I don't think there's an equivalent of Rust's compiler error index.