Node.js with File Handling – write / read
The Node.js API is a server-side programming technology. Hence, a Node.js application may be required to interact with the physical file system of the server. The Node.js API includes fs module that enables the developer to perform read/write operations on disk files. The fs module in Node.js provides synchronous as well as asynchronous methods for file handling.
To use the filesystem functions, you need to import the fs module using the following syntax −
var fs = require("fs")
Synchronous vs Asynchronous
Every method in the fs module has synchronous as well as asynchronous version. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error.
For example, the synchronous method for writing data in a file is
fs.writeFileSync(file, data[, options])
On the other hand, its asynchronous version has the following syntax
fs.writeFile(file, data[, options], callback)
The asynchronous methods are non-blocking in nature as compared to the synchronous methods.
For the example codes in this chapter, we will use a text file named example.txt with the following content
Javaskool.com provides self-learning content to teach the world in the easiest way!
Here’s a complete Node.js example that demonstrates writing, reading, and displaying the content of a file both synchronously and asynchronously
const fs = require('fs');
// Define the text content to write to the file
const text = `Javaskool.com provides self-learning content to teach the world in the easiest way!`;
// File path
const filePath = "example.txt";
// Function to write and read a file synchronously
function writeAndReadSync() {
console.log("Writing synchronously...");
try {
fs.writeFileSync(filePath, text); // Writing to the file synchronously
console.log("Write operation complete (synchronous).");
console.log("Reading synchronously...");
const data = fs.readFileSync(filePath, 'utf-8'); // Reading the file synchronously
console.log("File Content (synchronous):");
console.log(data);
} catch (err) {
console.error("Error in synchronous operation:", err);
}
}
// Function to write and read a file asynchronously
function writeAndReadAsync() {
console.log("Writing asynchronously...");
fs.writeFile(filePath, text, (err) => {
if (err) {
console.error("Error writing file asynchronously:", err);
return;
}
console.log("Write operation complete (asynchronous).");
console.log("Reading asynchronously...");
fs.readFile(filePath, 'utf-8', (err, data) => {
if (err) {
console.error("Error reading file asynchronously:", err);
return;
}
console.log("File Content (asynchronous):");
console.log(data);
});
});
}
// Execute synchronous operations
writeAndReadSync();
// Execute asynchronous operations
writeAndReadAsync();
Terminal Commands and logs
PS D:\React_Project\NodeProject> node NodeJsFileHandlingExample.js
Writing synchronously...
Write operation complete (synchronous).
Reading synchronously...
File Content (synchronous):
Javaskool.com provides self-learning content to teach the world in the easiest way!
Writing asynchronously...
Write operation complete (asynchronous).
Reading asynchronously...
File Content (asynchronous):
Javaskool.com provides self-learning content to teach the world in the easiest way!
PS D:\React_Project\NodeProject>
Recent Comments