Load a text file and find number of characters in the file - JavaScript

Suppose we have a data.txt file that lives in the same directory as our NodeJS file. Suppose the content of that file is −

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s.

We are required to write a JavaScript function that loads this external text file into our js file and returns the number of characters in this file.


Let’s write the code for this function −

const fs = require('fs');
const requireFile = async () => {
   const data = fs.readFileSync('./data.txt', 'utf-8');
   const len = data.length;
   return len;
requireFile().then(res => console.log(res)).catch(err => {
   console.log('some error occured');


The output in the console: −