How to Read Files in Node.js?

1. Definition

In Node.js, files are read using the built-in fs (File System) module. It allows you to read data from files asynchronously or synchronously.

2. Methods to Read Files

  • fs.readFile(): Asynchronous method
  • fs.readFileSync(): Synchronous method

3. Asynchronous Example

const fs = require("fs");

fs.readFile("example.txt", "utf8", (err, data) => {
  if (err) throw err;
  console.log(data);
});

4. Synchronous Example

const fs = require("fs");

const data = fs.readFileSync("example.txt", "utf8");
console.log(data);

5. Difference Between Async and Sync

  • Async: Non-blocking, faster, recommended
  • Sync: Blocking, slower, used for simple cases

6. Advantages

  • Easy file handling
  • Supports async operations
  • Built-in module (no installation needed)