How to read a File's contents in TypeScript

avatar

Borislav Hadzhiev

Sun Mar 27 20222 min read

banner

Photo by Alex Blăjan

Read a File's contents in TypeScript #

Use the readFileSync() method to read a file's contents in TypeScript, e.g. readFileSync(join(__dirname, 'example.txt'), 'utf-8'). The method takes the path and encoding as parameters and returns the contents of the specified file.

index.ts
import { readFileSync, promises as fsPromises } from 'fs'; import { join } from 'path'; // ✅ read file SYNCHRONOUSLY function syncReadFile(filename: string) { const result = readFileSync(join(__dirname, filename), 'utf-8'); console.log(result); // 👉️ "hello world hello world ..." return result; } syncReadFile('./example.txt'); // -------------------------------------------------------------- // ✅ read file ASYNCHRONOUSLY async function asyncReadFile(filename: string) { try { const result = await fsPromises.readFile( join(__dirname, filename), 'utf-8', ); console.log(result); // 👉️ "hello world hello world ..." return result; } catch (err) { console.log(err); return 'Something went wrong' } } asyncReadFile('./example.txt');

The function from the first example reads the contents of a file synchronously.

If you haven't installed the typings for node, make sure to run the following command:

shell
npm install --save-dev @types/node

if you get an error that the type declarations for the fs module are not found, add the node string to the types array in your tsconfig.json file.

tsconfig.json
{ "compilerOptions": { "types": [ "node" ] }, }

The fs.readFileSync method takes the path to the file as the first parameter and the encoding as the second.

The method returns the contents of the provided path.

If you omit the encoding parameter, the function will return a buffer, otherwise a string is returned.

The __dirname variable returns the directory name of the current module.

For example, if you use the __dirname variable in a module located at /home/user/my-module.js, the __dirname variable would return /home/user.

We used the path.join method to join the path of the directory of the current module with the provided filename.

The code snippet above assumes that there is an example.txt file located in the same directory as the current module.

For example, if the file you're reading is located one directory up, you'd pass ../example.txt as a parameter to the function.

Alternatively, you could use the fsPromises object to read a file asynchronously.

Use the fsPromises.readFile() method to read a file's contents asynchronously in TypeScript, e.g. const result = await fsPromises.readFile(join(__dirname, filename), 'utf-8');. The method takes the path and encoding as parameters and asynchronously reads the contents of the file.

index.ts
import { promises as fsPromises } from 'fs'; import { join } from 'path'; // ✅ read file ASYNC async function asyncReadFile(filename: string) { try { const result = await fsPromises.readFile( join(__dirname, filename), 'utf-8', ); console.log(result); // 👉️ "hello world hello world ..." return result; } catch (err) { console.log(err); return 'Something went wrong'; } } asyncReadFile('./example.txt');

The fsPromises.readFile() method asynchronously reads the contents of the provided file.

If you don't provide a value for the encoding parameter, the method returns a buffer, otherwise a string is returned.

The method returns a promise that fulfills with the contents of the file, so we have to await it or use the .then() method on it to get the resolved string.

Use the search field on my Home Page to filter through my more than 1,000 articles.