- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js Read and Write File
In the world of Node.js, interacting with the file system is a core task. Whether you are building a web server that needs to read configuration files, a logging system that records events, or a tool that processes CSV data, you will rely on the built-in fs (File System) module. This module provides everything you need to manage files and directories efficiently.
path module alongside fs to join paths securely.
Key Features of File Read/Write
- Asynchronous and Synchronous Operations: Node.js offers a choice. Asynchronous methods use callbacks (or Promises) to ensure your application remains responsive, while synchronous methods block execution until the task is finished.
- Error Handling: File operations are prone to external issues, such as missing files or restricted permissions. Using
try...catchor checking theerrargument in callbacks is essential. - Text and Binary Data: Node.js can handle plain text (like
.txtor.json) as well as binary data (like images or PDFs) using Buffers.
Reading Files
1. fs.readFile()
The fs.readFile() method is the standard way to read file contents without stopping the rest of your code. It reads the entire file into memory and then triggers a callback function.
const fs = require('fs');
// Reading a file asynchronously
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error("Failed to read file:", err.message);
return;
}
console.log("File content received:");
console.log(data);
});
Output:
Content of the example.txt file
- Encoding: Adding
'utf8'as the second argument tells Node.js to return the data as a readable string. If you omit this, Node.js will return aBufferobject (raw binary data).
<Buffer 48 65 6c 6c 6f> instead of actual text.
2. fs.readFileSync()
The fs.readFileSync() method is the "blocking" version. It is simpler to write because it returns the data directly, but it stops all other code execution until the file is read.
const fs = require('fs');
try {
const data = fs.readFileSync('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error("Error reading file synchronously:", err);
}
Output:
Content of the example.txt file
readFileSync is perfectly fine for CLI tools or during the initial "startup" phase of an application (like reading a config.json file) where you need the data before the app can even start.
Writing Files
1. fs.writeFile()
The fs.writeFile() method saves data to a file. If the file already exists, it is completely replaced. If it doesn't exist, Node.js creates it for you.
const fs = require('fs');
const content = 'Hello, Node.js! This is a fresh write.';
fs.writeFile('output.txt', content, (err) => {
if (err) throw err;
console.log('File written successfully');
});
Output:
File written successfully
fs.writeFile() is destructive. It does not check if a file has content; it simply overwrites everything. Always double-check your filenames!
2. fs.writeFileSync()
Similar to reading, this is the synchronous version of writing. It is useful when you need to ensure a file is written before moving on to the next logic step in a script.
const fs = require('fs');
const userData = JSON.stringify({ name: "John", age: 30 });
try {
fs.writeFileSync('user.json', userData);
console.log('User data saved successfully');
} catch (err) {
console.error('Save failed:', err);
}
Output:
User data saved successfully
3. fs.appendFile()
If you want to add data to an existing file without deleting what is already thereālike adding a new line to a log fileāuse fs.appendFile().
const fs = require('fs');
const logEntry = `\nLog Entry at ${new Date().toISOString()}`;
fs.appendFile('server.log', logEntry, (err) => {
if (err) throw err;
console.log('New log entry added!');
});
Output:
New log entry added!
\n) manually if you want each entry to appear on a new line.
Summary
Mastering the fs module is a milestone for any Node.js developer. You have two main paths: the Asynchronous path (readFile, writeFile), which is better for performance-critical applications like web servers, and the Synchronous path (readFileSync, writeFileSync), which is simpler for quick scripts and one-off tasks. By combining these methods with proper error handling and encoding, you can manage any data persistence needs your application requires.
require('fs').promises. This allows you to use async/await syntax, which is often cleaner and easier to read than nested callbacks.