Last updated: Feb 29, 2024
Reading timeยท3 min
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.
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');
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.
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');
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.
bobby hadz com
If you haven't installed the typings for Node.js, run the following command.
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.
{ "compilerOptions": { "types": [ "node" ] }, }
The fs.readFileSync method takes the path to the file as the first parameter and the encoding as the second.
const result = readFileSync(join(__dirname, filename), 'utf-8');
The method returns the contents of the provided path.
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.
../example.txt
as a parameter to the function.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.
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.
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');
If you need to get an array of the contents of the file, use the following code sample instead.
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');
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.
bobby hadz com
../example.txt
as a parameter to the function.asyncReadFile('../example.txt');
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.
You can learn more about the related topics by checking out the following tutorials: