How to read and write a file using JavaScript?

File operations in JavaScript are handled through Node.js using the built-in fs (File System) module. This module provides methods to read from and write to files asynchronously.

Writing Files with writeFile()

The writeFile() method creates a new file or overwrites an existing file with the specified content.

Syntax

fs.writeFile(path, data, options, callback)

Parameters

  • path: File path or filename where data will be written
  • data: Content to write to the file (string, buffer, or typed array)
  • options: Optional encoding (default: 'utf8') or options object
  • callback: Function called when operation completes, receives error parameter
If the file exists, writeFile() overwrites its contents completely. If the file doesn't exist, it creates a new file at the specified path.

Example

const fs = require('fs');

let content = "Hello from TutorialsPoint! This is sample file content.";

fs.writeFile('sample.txt', content, (err) => {
    if (err) {
        console.log("Error writing file:", err);
    } else {
        console.log("File written successfully!");
    }
});
File written successfully!

Reading Files with readFile()

The readFile() method reads the entire contents of a file asynchronously.

Syntax

fs.readFile(path, options, callback)

Parameters

  • path: File path to read from
  • options: Optional encoding (e.g., 'utf8') or options object
  • callback: Function called with (error, data) parameters

Example

const fs = require('fs');

fs.readFile('sample.txt', 'utf8', (err, data) => {
    if (err) {
        console.log("Error reading file:", err);
    } else {
        console.log("File contents:");
        console.log(data);
    }
});
File contents:
Hello from TutorialsPoint! This is sample file content.

Combined Read and Write Example

Here's a practical example that demonstrates both writing to and reading from a file in sequence:

const fs = require('fs');

console.log("Starting file operations...");

// Write to file first
fs.writeFile('data.txt', 'JavaScript file operations are powerful!', (err) => {
    if (err) {
        console.log("Write error:", err);
        return;
    }
    
    console.log("File written successfully!");
    console.log("Now reading the file...");
    
    // Read the file we just created
    fs.readFile('data.txt', 'utf8', (err, data) => {
        if (err) {
            console.log("Read error:", err);
        } else {
            console.log("File content: " + data);
        }
    });
});
Starting file operations...
File written successfully!
Now reading the file...
File content: JavaScript file operations are powerful!

Error Handling Best Practices

Always handle errors properly when working with file operations:

const fs = require('fs');

// Check if file exists before reading
fs.readFile('nonexistent.txt', 'utf8', (err, data) => {
    if (err) {
        if (err.code === 'ENOENT') {
            console.log("File does not exist");
        } else {
            console.log("Other error:", err.message);
        }
    } else {
        console.log("File data:", data);
    }
});
File does not exist

Key Points

  • File operations in JavaScript require Node.js environment
  • Always import the fs module first
  • File operations are asynchronous by default
  • Specify encoding ('utf8') when reading text files
  • Handle errors in callback functions

Conclusion

The Node.js fs module provides essential file operations through writeFile() and readFile() methods. Always handle errors properly and remember that these operations are asynchronous, requiring callback functions to process results.

Updated on: 2026-03-15T19:56:30+05:30

83K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements