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.

Using Synchronous File Reading

The synchronous approach reads the file immediately and blocks execution until complete:

const fs = require('fs');

const requireFile = () => {
    try {
        const data = fs.readFileSync('./data.txt', 'utf-8');
        const len = data.length;
        return len;
    } catch (error) {
        console.log('Error reading file:', error.message);
        return 0;
    }
};

const characterCount = requireFile();
console.log('Number of characters:', characterCount);
Number of characters: 399

Using Asynchronous File Reading

The asynchronous approach is better for performance as it doesn't block the main thread:

const fs = require('fs').promises;

const requireFile = async () => {
    try {
        const data = await fs.readFile('./data.txt', 'utf-8');
        return data.length;
    } catch (error) {
        console.log('Error reading file:', error.message);
        return 0;
    }
};

requireFile()
    .then(count => console.log('Character count:', count))
    .catch(err => console.log('Operation failed'));
Character count: 399

Handling Different Scenarios

Here's a more robust version that handles various file scenarios:

const fs = require('fs').promises;
const path = require('path');

const getFileCharacterCount = async (filename) => {
    try {
        const filePath = path.join(__dirname, filename);
        const data = await fs.readFile(filePath, 'utf-8');
        
        console.log(`File: ${filename}`);
        console.log(`Total characters: ${data.length}`);
        console.log(`Characters (excluding spaces): ${data.replace(/\s/g, '').length}`);
        console.log(`Lines: ${data.split('<br>').length}`);
        
        return data.length;
    } catch (error) {
        if (error.code === 'ENOENT') {
            console.log(`File ${filename} not found`);
        } else {
            console.log('Error:', error.message);
        }
        return 0;
    }
};

getFileCharacterCount('data.txt');
File: data.txt
Total characters: 399
Characters (excluding spaces): 337
Lines: 1

Comparison of Methods

Method Blocking Performance Best For
fs.readFileSync() Yes Slower for large files Simple scripts, small files
fs.readFile() No Better for large files Production applications

Conclusion

Use fs.readFile() with async/await for non-blocking file operations. Always include error handling to manage missing files or permission issues gracefully.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements