Last updated: Feb 29, 2024
Reading timeยท3 min
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.
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');
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:
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.
{ "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.
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".
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.
../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.
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.
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');
The fsPromises.writeFile method asynchronously writes data to a file replacing the file's contents if the file already exists.
await fsPromises.writeFile(join(__dirname, filename), data, { flag: 'w', });
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.
You can learn more about the related topics by checking out the following tutorials: