To read a file in TypeScript, you can use the built-in fs
module in Node.js. Here is an example that demonstrates how to read a file, decode the contents as UTF-8, and log the result to the console:
index.ts197 chars12 lines
In the code above, we first import the fs
module from Node.js. We then specify the path to the file that we want to read in the filePath
constant. We use the fs.readFile
method to read the contents of the file, specifying 'utf-8'
as the encoding to use. The result is passed to a callback function that logs the data to the console.
Note that fs.readFile
returns the file contents as a Buffer
if no encoding is specified. If you want to work with the file contents as a Buffer
, omit the encoding parameter:
index.ts206 chars12 lines
In this case, we use data.toString('utf-8')
to convert the Buffer
to a string before logging it to the console.
gistlibby LogSnag