Open In App

Node.js File System

Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js helps developers to write JavaScript code to run on the server-side, to generate dynamic content and deliver to the web clients. The two features that make Node.js stand-out are:

About Node.js file system: To handle file operations like creating, reading, deleting, etc., Node.js provides an inbuilt module called FS (File System). Node.js gives the functionality of file I/O by providing wrappers around the standard POSIX functions. All file system operations can have synchronous and asynchronous forms depending upon user requirements. To use this File System module, use the require() method:



var fs = require('fs');

Common use for File System module:

What is Synchronous and Asynchronous approach?



GeeksforGeeks: A computer science portal




var fs = require("fs");
 
// Asynchronous read
fs.readFile('input.txt', function (err, data) {
   if (err) {
      return console.error(err);
   }
   console.log("Asynchronous read: " + data.toString());
});

Asynchronous read: GeeksforGeeks: A computer science portal




var fs = require("fs");
 
// Synchronous read
var data = fs.readFileSync('input.txt');
console.log("Synchronous read: " + data.toString());

Synchronous read: GeeksforGeeks: A computer science portal

Open a File: The fs.open() method is used to create, read, or write a file. The fs.readFile() method is only for reading the file and fs.writeFile() method is only for writing to the file, whereas fs.open() method does several operations on a file. First, we need to load the fs class which is a module to access the physical file system. Syntax:

fs.open(path, flags, mode, callback)

Parameters:

Example: Let us create a js file named main.js having the following code to open a file input.txt for reading and writing. 




var fs = require("fs");
 
// Asynchronous - Opening File
console.log("opening file!");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File open successfully");    
});

Output:

opening file!
File open successfully

Reading a File: The fs.read() method is used to read the file specified by fd. This method reads the entire file into the buffer. Syntax:

fs.read(fd, buffer, offset, length, position, callback)

Parameters:

Example: Let us create a js file named main.js having the following code: 




var fs = require("fs");
var buf = new Buffer(1024);
 
console.log("opening an existing file");
fs.open('input.txt', 'r+', function(err, fd) {
   if (err) {
      return console.error(err);
   }
   console.log("File opened successfully!");
   console.log("reading the file");
    
   fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
      if (err){
         console.log(err);
      }
      console.log(bytes + " bytes read");
       
      // Print only read bytes to avoid junk.
      if(bytes > 0){
         console.log(buf.slice(0, bytes).toString());
      }
   });
});

Output:

opening an existing file
File opened successfully!
reading the file
40 bytes read
GeeksforGeeks: A computer science portal

Writing to a File: This method will overwrite the file if the file already exists. The fs.writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method. Syntax:

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

Parameters:

Example: Let us create a js file named main.js having the following code: 




var fs = require("fs");
 
console.log("writing into existing file");
fs.writeFile('input.txt', 'Geeks For Geeks', function(err) {
   if (err) {
      return console.error(err);
   }
    
   console.log("Data written successfully!");
   console.log("Let's read newly written data");
    
   fs.readFile('input.txt', function (err, data) {
      if (err) {
         return console.error(err);
      }
      console.log("Asynchronous read: " + data.toString());
   });
});

Output:

writing into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Geeks For Geeks

Appending to a File: The fs.appendFile() method is used to synchronously append the data to the file. Syntax:

fs.appendFile(filepath, data, options, callback);

or

fs.appendFileSync(filepath, data, options);

Parameters:

Example 1: Let us create a js file named main.js having the following code: 




var fs = require('fs');
  
var data = "\nLearn Node.js";
  
// Append data to file
fs.appendFile('input.txt', data, 'utf8',
 
    // Callback function
    function(err) {
        if (err) throw err;
 
        //  If no error
        console.log("Data is appended to file successfully.")
});

Output:

Data is appended to file successfully.

Example 1: For synchronously appending 




var fs = require('fs');
  
var data = "\nLearn Node.js";
  
// Append data to file
fs.appendFileSync('input.txt', data, 'utf8');
console.log("Data is appended to file successfully.")

Output:

Data is appended to file successfully.
GeeksforGeeks: A computer science portal 
GeeksforGeeks: A computer science portal
Learn Node.js

Closing the File: The fs.close() method is used to asynchronously close the given file descriptor thereby clearing the file that is associated with it. This will allow the file descriptor to be reused for other files. Calling fs.close() on a file descriptor while some other operation is being performed on it may lead to undefined behavior. Syntax:

fs.close(fd, callback)

Parameters:

Example: Let us create a js file named main.js having the following code: 




// Close the opened file.
fs.close(fd, function(err) {
   if (err) {
      console.log(err);
   }
   console.log("File closed successfully.");
}

Output:

File closed successfully.

Delete a File: The fs.unlink() method is used to remove a file or symbolic link from the filesystem. This function does not work on directories, therefore it is recommended to use fs.rmdir() to remove a directory. Syntax:

fs.unlink(path, callback)

Parameters:

Example: Let us create a js file named main.js having the following code: 




var fs = require("fs");
 
console.log("deleting an existing file");
fs.unlink('input.txt', function(err) {
   if (err) {
      return console.error(err);
   }
   console.log("File deleted successfully!");
});

Output:

deleting an existing file
File deleted successfully!

Article Tags :