Introduction: Reading files with Node

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


The simplest way to read a file in Node is to use the fs.readFile() method, passing it the file path and a callback function that will be called with the file data (and the error):

const fs = require('fs')

fs.readFile('/Users/flavio/test.txt', (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(data)
})

Alternatively, you can use the synchronous version fs.readFileSync():

const fs = require('fs')

try {
  const data = fs.readFileSync('/Users/flavio/test.txt', 'utf8')
  console.log(data)
} catch (err) {
  console.error(err)
}

The default encoding is utf8, but you can specify a custom encoding using a a second parameter.

Both fs.readFile() and fs.readFileSync() read the full content of the file in memory before returning the data.

This means that big files are going to have a major impact on your memory consumption and speed of execution of the program.

In this case, a better option is to read the file content using streams.

Lessons in this unit:

0: Introduction
1: Installing Node.js on your computer
2: How to write your first Node.js program
3: Importing other files
4: Using npm to install packages
5: Using built-in modules
6: How to use the Node.js REPL
7: ▶︎ Reading files with Node
8: Writing files with Node
9: Build an HTTP Server
10: The Node Event emitter
11: How to read environment variables from Node.js
12: Node Buffers
13: Node.js Streams
14: How to use promises and await with Node.js callback-based functions
15: Modern package managers (pnpm and Bun)