Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Reading Files
tutorial

Reading Files

Imagine you have a diary filled with your thoughts. To read what you wrote yesterday, you need to open the diary and flip to the right page. In Node.js, reading files is just like that – you open a file and read its contents. Let's learn how to do that!

Reading Files in Node.js

Node.js provides several ways to read files. The most common methods are:
  • Asynchronous reading (non-blocking) – recommended
  • Synchronous reading (blocking) – simpler but not ideal for production
  • Promise-based reading – modern async/await style

Think of asynchronous reading like ordering food at a restaurant – you place your order and continue chatting while the kitchen prepares your food. Synchronous reading is like cooking yourself – you can't do anything else until it's done.

1. Asynchronous Reading (Recommended)

The asynchronous method doesn't block the execution. It takes a callback function that runs when the file is read.
const fs = require('fs');

<!-- Read a file asynchronously -->
fs.readFile('sample.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log('File content:', data);
});

console.log('This prints first because reading is async!');

2. Synchronous Reading

The synchronous method blocks execution until the file is read. Method names end with `Sync`.
const fs = require('fs');

try {
  const data = fs.readFileSync('sample.txt', 'utf8');
  console.log('File content:', data);
} catch (err) {
  console.error('Error reading file:', err);
}

console.log('This prints after reading (synchronous)');

3. Promise-based Reading (Modern)

Node.js provides a promises API that works beautifully with async/await.
const fs = require('fs').promises;

async function readFileAsync() {
  try {
    const data = await fs.readFile('sample.txt', 'utf8');
    console.log('File content:', data);
  } catch (err) {
    console.error('Error:', err);
  }
}

readFileAsync();

Reading Different File Types

File TypeEncodingExample
Text files'utf8'`fs.readFile('notes.txt', 'utf8', callback)`
JSON files'utf8' + JSON.parse`const data = JSON.parse(await fs.readFile('config.json'))`
Binary filesNo encoding (returns Buffer)`fs.readFile('image.jpg', callback)`

Reading JSON Files (Practical Example)
const fs = require('fs').promises;

async function readConfig() {
  try {
    const data = await fs.readFile('config.json', 'utf8');
    const config = JSON.parse(data);
    console.log('Server port:', config.port);
    console.log('Database URL:', config.database.url);
  } catch (err) {
    console.error('Failed to read config:', err);
  }
}

readConfig();

Error Handling in File Reading

Always handle errors! Common errors include:
  • ENOENT: File doesn't exist
  • EACCES: Permission denied
  • EISDIR: Trying to read a directory as a file
fs.readFile('missing.txt', 'utf8', (err, data) => {
  if (err) {
    if (err.code === 'ENOENT') {
      console.log('File not found. Please check the filename.');
    } else {
      console.error('An error occurred:', err.message);
    }
    return;
  }
  console.log(data);
});

Reading Files with Path Module

Combine with `path` module for reliable file paths.
const fs = require('fs');
const path = require('path');

<!-- Build path to file in same directory -->
const filePath = path.join(__dirname, 'data', 'users.json');

fs.readFile(filePath, 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading users file:', err);
    return;
  }
 
  const users = JSON.parse(data);
  console.log('Total users:', users.length);
});

Two Minute Drill

  • Use `fs.readFile()` for asynchronous non-blocking file reading.
  • Use `fs.readFileSync()` for simple scripts but avoid in production servers.
  • For modern code, use `fs.promises` with async/await.
  • Always specify encoding ('utf8') for text files, omit for binary files.
  • Handle errors properly – check error codes like 'ENOENT'.
  • Combine with `path` module for cross-platform file paths.

Need more clarification?

Drop us an email at career@quipoinfotech.com