How to read a File's contents in TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 29, 2024
3 min

banner

# Read a File's contents synchronously in TypeScript

Use the readFileSync() method to read a file's contents in TypeScript.

The method takes the path and encoding as parameters and returns the contents of the specified file.

index.ts
import { readFileSync } from 'fs'; import { join } from 'path'; function syncReadFile(filename: string) { const result = readFileSync(join(__dirname, filename), 'utf-8'); // bobby // hadz // com console.log(result); return result; } syncReadFile('./example.txt');

file read successfully

The code for this article is available on GitHub

The function takes a file name and reads the contents of the file synchronously, returning a string.

If you need to get an array of the contents of the file, use the following code sample instead.

index.ts
import { readFileSync } from 'fs'; import { join } from 'path'; function syncReadFile(filename: string) { const contents = readFileSync(join(__dirname, filename), 'utf-8'); const arr = contents.split(/\r?\n/); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ] // โœ… Read file line by line arr.forEach((line) => { // bobby // hadz // com console.log(line); }); return arr; } syncReadFile('./example.txt');

typescript read file line by line

The code for this article is available on GitHub

You can use the forEach() method to read the contents of the file line by line.

The code sample assumes that you have an example.txt file located in the same directory as the index.ts script.

example.txt
bobby hadz com

If you haven't installed the typings for Node.js, 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.

index.ts
const result = readFileSync(join(__dirname, filename), 'utf-8');

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 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.
index.ts
syncReadFile('../example.txt');

I've also written an article on how to write to a file using TypeScript.

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

# Read a File's contents asynchronously in TypeScript

If you need to read a file's contents asynchronously, use the fsPromises.readFile() method.

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'; async function asyncReadFile(filename: string) { try { const result = await fsPromises.readFile( join(__dirname, filename), 'utf-8', ); // bobby // hadz // com console.log(result); return result; } catch (err) { console.log(err); return 'Something went wrong'; } } asyncReadFile('./example.txt');

file read successfully

The code for this article is available on GitHub

If you need to get an array of the contents of the file, use the following code sample instead.

index.ts
import { promises as fsPromises } from 'fs'; import { join } from 'path'; async function asyncReadFile(filename: string) { try { const contents = await fsPromises.readFile( join(__dirname, filename), 'utf-8', ); const arr = contents.split(/\r?\n/); console.log(arr); // ๐Ÿ‘‰๏ธ [ 'bobby', 'hadz', 'com' ] // โœ… Read file line by line arr.forEach((line) => { // bobby // hadz // com console.log(line); }); return arr; } catch (err) { console.log(err); return 'Something went wrong'; } } asyncReadFile('./example.txt');
The code for this article is available on GitHub

You can use the forEach() method to read the contents of the file line by line.

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

The code sample assumes that you have an example.txt file located in the same directory as the index.ts script.

example.txt
bobby hadz com
For example, if the file you're reading is located one directory up, you'd pass ../example.txt as a parameter to the function.
index.ts
asyncReadFile('../example.txt');
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 resolves with the contents of the file, so we have to await it or use the .then() method on it to get the resolved string.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev