How to write to a File using TypeScript

avatar
Borislav Hadzhiev

Last updated: Feb 29, 2024
3 min

banner

# Table of Contents

  1. Write to a File synchronously using TypeScript
  2. Write to a file asynchronously in TypeScript

# Write to a File synchronously using TypeScript

Use the fs.writeFileSync() method to write to a file in TypeScript.

The method takes the path to the file, the data and an options object as parameters and writes the provided content to the file.

index.ts
import { readFileSync, writeFileSync } from 'fs'; import { join } from 'path'; // โœ… write to file SYNCHRONOUSLY function syncWriteFile(filename: string, data: any) { /** * flags: * - w = Open file for reading and writing. File is created if not exists * - a+ = Open file for reading and appending. The file is created if not exists */ writeFileSync(join(__dirname, filename), data, { flag: 'w', }); const contents = readFileSync(join(__dirname, filename), 'utf-8'); console.log(contents); // ๐Ÿ‘‰๏ธ "One Two Three Four" return contents; } syncWriteFile('./example.txt', 'One\nTwo\nThree\nFour');

typescript write to file

The code for this article is available on GitHub

The syncWriteFile function takes a filename and a string and writes the string to the file.

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 aren't found, add the node string to the types array in your tsconfig.json file.

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

The fs.writeFileSync method takes the path to the file as the first parameter, the data as the second and an options object as the third.

index.ts
writeFileSync(join(__dirname, filename), data, { flag: 'w', });

The flag property in the options object is set to w by default, which means - "Open the file for writing and create it if it doesn't exist".

If you want to append data to the file, use the a+ flag instead, which opens a file for reading and appending and also creates the file if it doesn't exist.

You can view the other available flag values in this section of the Node.js docs.

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 sample above writes to a file called example.txt that is located in the same directory as the current module.

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

I've also written an article on how to read a file's contents in TS.

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

# Write to a file asynchronously in TypeScript

If you need to write to a file asynchronously, use the fsPromises.writeFile() method.

The method takes the path and the data as parameters and asynchronously writes the data to the file.

index.ts
import { promises as fsPromises } from 'fs'; import { join } from 'path'; // โœ… write to file ASYNCHRONOUSLY async function asyncWriteFile(filename: string, data: any) { /** * flags: * - w = Open file for reading and writing. File is created if not exists * - a+ = Open file for reading and appending. The file is created if not exists */ try { await fsPromises.writeFile(join(__dirname, filename), data, { flag: 'w', }); const contents = await fsPromises.readFile( join(__dirname, filename), 'utf-8', ); console.log(contents); // ๐Ÿ‘‰๏ธ "One Two Three Four" return contents; } catch (err) { console.log(err); return 'Something went wrong'; } } asyncWriteFile('./example.txt', 'One\nTwo\nThree\nFour');

typescript write to file

The code for this article is available on GitHub

The fsPromises.writeFile method asynchronously writes data to a file replacing the file's contents if the file already exists.

index.ts
await fsPromises.writeFile(join(__dirname, filename), data, { flag: 'w', });
If you want to append to the file, set a+ for the value of the flag property in the options object.

The method returns a promise that resolves with undefined upon success.

The code sample above writes to a file called example.txt that is located in the same directory as the current module.

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

The code for this article is available on GitHub

# 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