Categories
TypeScript Answers

How to read and write a text file in TypeScript?

Spread the love

Sometimes, we want to read and write a text file in TypeScript.

In this article, we’ll look at how to read and write a text file in TypeScript.

How to read and write a text file in TypeScript?

To read and write a text file in TypeScript, we should install the @types/node package to add the typings for core Node modules.

To install it, we run

npm i @types/node

to add the node.d.ts file into our project which has the typings for the core Node modules.

Then we can us the fs.readFileSync method to read a file by writing

import * as fs from "fs";
const f = fs.readFileSync("foo.txt", "utf8");

to call readFileSync with the path of the file and the encoding of the file to return the file.

Conclusion

To read and write a text file in TypeScript, we should install the @types/node package to add the typings for core Node modules.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *