JavaScript:Node.js File System (fs): Reading and Writing Files
JavaScript•File I/O

Node.js File System (fs): Reading and Writing Files

Explore the Node.js file system API using modern promise-based fs.writeFile, fs.readFile, and path utilities.

Syntax

import fs from "fs/promises"; await fs.writeFile("file.txt", "data");

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
fs.writeFileAsync MethodWrites data to file asynchronously.
fs.readFileAsync MethodReads contents of file asynchronously.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Node.js In-Memory Stream Buffer Simulation
const EventEmitter = require("events");

class VirtualLogStream extends EventEmitter {
  constructor() {
    super();
    this.buffer = [];
  }

  writeLog(message) {
    const timestamp = new Date().toISOString();
    const entry = "[" + timestamp + "] " + message;
    this.buffer.push(entry);
    this.emit("data", entry);
  }

  getContents() {
    return this.buffer.join("\n");
  }
}

const logger = new VirtualLogStream();
logger.on("data", entry => console.log("Stream Event: " + entry.split("] ")[1]));

logger.writeLog("System initialization sequence started.");
logger.writeLog("Port 8080 listening for inbound traffic.");
logger.writeLog("Database pool connected successfully.");
Expected Output:
Stream Event: System initialization sequence started.
Stream Event: Port 8080 listening for inbound traffic.
Stream Event: Database pool connected successfully.

How It Works: Step-by-Step

  • Lines 4-18: Simulates streaming I/O using Node.js core EventEmitter.
  • Line 21: Registers event listener on stream data chunks.
  • Lines 23-25: Writes log entries and flushes them to listener.

Key Concepts

  • Node.js provides fs/promises for promise-based file operations.
  • Streams (fs.createReadStream) are used for handling large files without exhausting RAM.
  • Always specify character encoding (e.g., "utf-8") when reading text files.

Common Mistake: Forgetting to specify utf-8 encoding when reading files with fs.readFile

Without encoding, fs.readFile returns a raw Buffer of bytes instead of a string.

❌ Incorrect
const data = await fs.readFile("file.txt"); // data is a Buffer object!
✅ Correct
const data = await fs.readFile("file.txt", "utf-8"); // data is a string

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler