Reading a text file into an Array in Node.js

Reading text files into arrays is a common task in Node.js applications. The built-in fs module provides both synchronous and asynchronous methods to read files and convert their content into arrays by splitting lines.

Using fs.readFileSync() (Synchronous)

The synchronous approach blocks code execution until the file is completely read. This method is suitable for smaller files or when you need the data immediately.

// Importing the fs module
const fs = require("fs");

// Function to read file and convert to array
const readFileLines = filename =>
  fs.readFileSync(filename)
  .toString('UTF8')
  .split('<br>');

// Reading the file into array
let arr = readFileLines('sample.txt');

// Printing the array
console.log(arr);

Assuming sample.txt contains:

Welcome to TutorialsPoint !
SIMPLY LEARNING
JavaScript Tutorial
[ 'Welcome to TutorialsPoint !',
  'SIMPLY LEARNING', 
  'JavaScript Tutorial' ]

Using fs.readFile() (Asynchronous)

The asynchronous approach is non-blocking and recommended for production applications, especially when dealing with larger files or when performance is critical.

// Importing the fs module
const fs = require("fs");

// Reading file asynchronously
fs.readFile('sample.txt', 'utf8', function(err, data) {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  
  // Convert file content to array
  const array = data.toString().split("<br>");
  
  // Process each line
  array.forEach((line, index) => {
    console.log(`Line ${index + 1}: ${line}`);
  });
});

console.log("File reading started...");
File reading started...
Line 1: Welcome to TutorialsPoint !
Line 2: SIMPLY LEARNING
Line 3: JavaScript Tutorial

Using Promises with fs.readFile()

For modern JavaScript development, you can wrap fs.readFile() in a Promise or use the fs.promises API for cleaner async/await syntax.

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

// Using async/await with fs.promises
async function readFileToArray(filename) {
  try {
    const data = await fs.readFile(filename, 'utf8');
    return data.split('<br>');
  } catch (error) {
    console.error('Error reading file:', error);
    return [];
  }
}

// Usage
readFileToArray('sample.txt').then(lines => {
  console.log('Total lines:', lines.length);
  lines.forEach((line, index) => {
    if (line.trim()) { // Skip empty lines
      console.log(`${index + 1}: ${line}`);
    }
  });
});
Total lines: 3
1: Welcome to TutorialsPoint !
2: SIMPLY LEARNING
3: JavaScript Tutorial

Comparison of Methods

Method Blocking Best For Error Handling
readFileSync() Yes Small files, simple scripts Try/catch required
readFile() No Production apps, large files Callback-based
fs.promises No Modern async/await code Promise-based

Key Points

  • Always specify encoding ('utf8') to get string data instead of Buffer
  • Use split('
    ')
    to convert file content into an array of lines
  • Handle empty lines by checking line.trim() if needed
  • Prefer asynchronous methods for better performance in production

Conclusion

Node.js provides multiple ways to read text files into arrays. Use readFileSync() for simple scripts and readFile() or fs.promises for production applications where non-blocking operations are essential.

Updated on: 2026-03-15T23:19:00+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements