Node.js gives the functionality of File I/O by providing wrappers around the standard POSIX functions.
In Node.js, File I/O methods can be performed in both synchronous as well as asynchronous form depending
upon the user requirements. In order to use this functionalities we need to require the fs module as
shown below :
var fs = require('fs');
There are two ways for Reading a file in nodejs :
//Reading a File Asynchronously using nodejs
var fs=require('fs');
fs.readFile('message.txt', (err, data) => {
if (err)
throw err;
console.log("Content : " + data);
});
var fs = require('fs');
var filename = 'content.txt'; //Name of the file to be read
var content = fs.readFileSync(filename);
console.log('Content : ' + content);
There are two ways for writing a file in nodejs :
//Writing a File Asynchronously using nodejs
var fs = require('fs');
var content= "this is the content in the file";
fs.writeFile('message.txt', content , (err) => {
if (err)
throw err;
console.log('It\'s saved!');
});
var fs = require('fs');
var content = "We are writing this file synchronously using node.js";
fs.writeFileSync('content.txt', content);
console.log("File Written Successfully");
There are two ways for Appending a file using nodejs :
//Writing a File Asynchronously using nodejs
var fs = require('fs');
new_data = "This data will be appended at the end of the file.";
fs.appendFile('input.txt', new_data , (err) => {
if(err)
throw err;
console.log('The new_content was appended successfully');
});
//file append operation in nodejs
var fs = require('fs');
var content = "We are Appending this file synchronously using node.js";
fs.appendFileSync('input.txt', content);
console.log("File Appended Successfully");
There are two ways for Renaming a file in nodejs :
var fs = require('fs');
//you have to pass the Relative path of the file from the Current working directory.
fs.rename('data.txt', 'new_data.txt', (err) => {
if (err)
throw err;
console.log('File renamed successfully');
});
//To check it's Asynchronous nature !
console.log("This method is Asynchronous");
var fs = require('fs');
//you have to pass the Relative path of the file from the Current working directory.
fs.renameSync('data.txt', 'newData.txt');
console.log('File renamed successfully');
// To check it's Synchronous nature !
console.log("This method is Synchronous");
There are two ways for deleting a file in nodejs :
var fs = require('fs');
var filename = 'content.txt';
fs.unlink(filename, (err) => {
if (err)
throw err;
console.log('File deleted successfully');
});
var fs = require('fs');
var filename = 'data.txt';
fs.unlinkSync(filename);
console.log('File Deleted Successfully');
In this part of node.js tutorial series we learned about file system in node.js which includes :