How to write to a File using TypeScript

avatar

Borislav Hadzhiev

Sun Mar 27 20223 min read

Write to a File using TypeScript #

Use the fs.writeFileSync() method to write to a file in TypeScript, e.g. writeFileSync(join(__dirname, filename), data). 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, promises as fsPromises } 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'); // -------------------------------------------------------------- // ✅ 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');

The first function from the code snippet writes to 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.writeFileSync method takes the path to the file as the first parameter, the data as the second and an options object as the third.

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 snippet 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.

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

Use the fsPromises.writeFile() method to write to a file asynchronously in TypeScript, e.g. await fsPromises.writeFile(join(__dirname, filename), data). The method takes the path and the data as parameters and asynchronously writes the data to the file.

index.ts
// ✅ 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');

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

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 fulfills with undefined upon success.

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