To read a JSON file in TypeScript, you can use the built-in fs
(file system) module in Node.js. Here is an example:
index.ts357 chars14 lines
In this example, we are first importing the fs
module. We then define the path to our JSON file using a relative file path. We then use the readFileSync
method of fs
to read the contents of the file. We pass in the file path and a character encoding (in this case 'utf-8'
) as arguments to readFileSync
.
The result of readFileSync
is a string containing the JSON data. We then use JSON.parse
to parse the string into a JavaScript object.
Finally, we can access our JSON data as a regular JavaScript object and log it to the console.
Note that you may want to handle errors when reading the file using try
/catch
blocks.
gistlibby LogSnag