Skip to content

Reading and Writing Files

Node.js provides a built-in fs module to interact with the file system. It allows you to perform various operations like reading files, writing data, and managing directories. This guide covers how to read and write files using the fs module in both asynchronous and synchronous ways.

Reading Files

Node.js provides both asynchronous and synchronous methods for reading files.

Asynchronous File Read

The asynchronous method is non-blocking, meaning it doesn’t block the rest of the program while waiting for the file to be read.

const fs = require("fs");
fs.readFile("example.txt", "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
return;
}
console.log("File contents:", data);
});
  1. fs.readFile(): This method reads a file asynchronously. It takes three parameters:
  • The path of the file ('example.txt').
  • The encoding ('utf8'), which specifies the character encoding to use while reading the file.
  • A callback function that is executed when the file has been read. It takes two arguments: err (error, if any) and data (file contents).
  1. Error Handling: The callback function checks if there is an error (err). If there’s an error, it logs the error message; otherwise, it prints the file contents.

Synchronous File Read

Here is an example of how to read a file using fs.readFileSync:

const fs = require("fs");
try {
const data = fs.readFileSync("example.txt", "utf8");
console.log("File contents:", data);
} catch (err) {
console.error("Error reading file:", err);
}
  1. fs.readFileSync(): This method reads the contents of a file synchronously. It takes two parameters:
    • The path of the file ('example.txt' in this case).
    • The encoding ('utf8'), which specifies the character encoding used to read the file.
  2. Error Handling: The try...catch block ensures that if there is an error reading the file (e.g., the file does not exist), the error is caught and logged.

Writing Files

Node.js provides methods to write to files. Both synchronous and asynchronous methods are available.

Asynchronous File Write

Use the fs.writeFile() method to write to a file asynchronously:

const fs = require("fs");
const content = "Hello, Node.js!";
fs.writeFile("output.txt", content, "utf8", (err) => {
if (err) {
console.error("Error writing file:", err);
return;
}
console.log("File successfully written!");
});
  1. fs.writeFile(): This method writes data to a file asynchronously. It takes four parameters:

    • The path of the file ('output.txt').
    • The data to be written (content).
    • The encoding ('utf8'), which specifies how the data is written.
    • A callback function that is called after the file operation is complete. It takes one argument: err (error, if any).
  2. Error Handling: The callback function checks if there is an error (err). If there’s an error, it logs the error message. If no error occurs, it confirms that the file was successfully written.

Synchronous File Write

For a blocking write operation, use fs.writeFileSync():

const fs = require("fs");
const content = "Hello, Node.js!";
try {
fs.writeFileSync("output.txt", content, "utf8");
console.log("File successfully written!");
} catch (err) {
console.error("Error writing file:", err);
}
  1. fs.writeFileSync(): This method writes data to a file synchronously. It takes three parameters:

    • The path of the file ('output.txt').
    • The data to be written (content).
    • The encoding ('utf8'), which specifies how the data is written.
  2. Error Handling: The try...catch block ensures that if there is an error (e.g., permission issues), the error is caught and logged. If no error occurs, the console logs a success message.