read a file and print the contents of the file in typescript

To read a file and print its contents in TypeScript, you can make use of the Node.js file system module. First, you need to import the 'fs' module from Node.js. Once you have the file system module imported, you can use it to read the contents of a file and print it to the console.

index.ts
import * as fs from 'fs'; //import the 'fs' module

fs.readFile('filename.txt', 'utf8', (err, data) => {
    if (err) { //if an error occurs while reading the file
        console.error(err); //print the error message to the console
        return;
    }
    console.log(data); //if no error occurs, print the contents of the file to the console
});
350 chars
10 lines

In the above code, the readFile function is used to read the contents of the file. The first argument is the name of the file to be read. The second argument specifies the encoding of the file, which is set to 'utf8' in this case. The third argument is a callback function that is called once the file has been read. If an error occurs while reading the file, the error message is printed to the console. If no error occurs, the contents of the file are printed to the console using the console.log function.

gistlibby LogSnag