How to read files in Node.js

Reading files is essential for configuration loading, data processing, and content serving in Node.js applications and server-side development. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented file reading in numerous Node.js build tools, documentation generators, and template processors for CoreUI projects. From my expertise, the most versatile approach is to use the fs.readFile() method for asynchronous file operations. This method prevents blocking the event loop and provides better performance in web applications that handle multiple concurrent requests.

Use fs.readFile() method to asynchronously read file content without blocking the event loop.

const fs = require('fs')
fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err
  console.log(data)
})

The fs.readFile() method asynchronously reads the entire contents of a file. The first parameter is the file path, the second specifies the encoding (‘utf8’ for text files), and the third is a callback function that receives any error and the file data. This non-blocking approach allows your application to continue processing other requests while file operations complete. For JSON files, parse the data with JSON.parse(data) after reading.

Best Practice Note:

This is the same approach we use in CoreUI build processes for reading configuration files and templates. For synchronous operations during startup, use fs.readFileSync(), but prefer the async version for runtime file operations to maintain application responsiveness.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author