Node js File System

In node.js, 'fs' module handles file system I/O operations such as reading to and writing from files. There are synchronous and asynchronous methods in the library.

Read File

For this first create a text file, write the text that you want to print and save as 'input.txt'.

In next step, create a node.js file, copy and paste this code and save as readfile.js. Make sure the both files are placed in the same directory.

In this code, we call filestream(fs) module using the require method. The readFileSync() function is used to read text. readFileSync() does not take a callback. If we want to take a call back, then replace readFileSync with readFile.

var fs = require("fs");
var data = fs.readFileSync('input.txt');
console.log("Read file successfully");
console.log("Process Complete!");

Open command prompt and run this -

node readfile.js

Node.js Non Blocking code to read file

In the previous example, we have used readFileSync() to read the file. That is blocking code example. That process stops the code until complete. Here, we are using non blocking code to read text file data. For this we will call readFile() method of the file stream. This process takes less execution time.

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err) return console.error(err);
   console.log("Read file successfully");

console.log("Process Complete!");

Write file

The writeFile() method is used to write data to a file asynchronously. If file already exists, then it overwrites the existing content otherwise it creates a new file and writes data into it. To write the data in a file, execute the following code.

var fs = require('fs');
fs.writeFile('text.txt', 'Hello World!', function (err) {
if (err) throw err;
console.log('Writing is done.');

Open file

The open() method is used to open a file for reading or writing.

Syntax of open file-, flags[, mode], callback)

Description of parameters -

  • path - full path of the file with filename.
  • flags - behaviour of the file to be opened.
  • mode - The mode of open files, like - read, write, readwrite. The default value is 0666 readwrite.
  • callback - This will called after opening the file, it accepts two parameters - err , fd.'text.txt', 'r', function (err, file) {
if (err){
console.log('File opened.');

Delete file

The unlink() method is used to delete an existing file.

fs.unlink(path, callback);

Read more articles

General Knowledge

Learn Popular Language