top of page

Node.js File System


Node implements File Input/Output using a simple wrappers around its standard POSIX functions. The Node File System (fs) module is imported by the following syntax:

var fs = require("fs")



Synchronous vs Asynchronous


Every method in the fs module has synchronous as well as asynchronous forms. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error. It is better to use an asynchronous method instead of a synchronous method, as an asynchronous method never blocks a program during its execution, whereas a synchronous method does.


Example:

Create a text file named sample.txt with the following content:

We want to learn Node.js File System in an easy and understandable way!!

Let us create a js file named sample.js with the code:

var fs = require("fs");

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

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

console.log("Program Ended");

Now run the sample.js to see the result −

$ node main.js

Output.

Synchronous read: We want to learn Node.js File System in an easy and understandable way!!

Program Ended
Asynchronous read: We want to learn Node.js File System in an easy and understandable way!!

Now we are going to learn the major File I/O methods.


1. Open a File


Syntax:

Following is the syntax of the method to open a file in asynchronous mode −

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

Parameters:

Here is the description of the parameters used:

  • path: This is the string having file name including path.

  • flags: Flags indicate the behavior of the file to be opened. All possible values have been mentioned below.

  • mode: It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable.

  • callback: This is the callback function which gets two arguments (err, fd).


Flags

Flags for read/write operations are:

  1. r: Open file for reading. An exception occurs if the file does not exist.

  2. r+: Open file for reading and writing. An exception occurs if the file does not exist.

  3. rs: Open file for reading in synchronous mode.

  4. rs+: Open file for reading and writing, asking the OS to open it synchronously. See notes for 'rs' about using this with caution.

  5. w: Open file for writing. The file is created (if it does not exist) or truncated (if it exists).

  6. wx: Like 'w' but fails if the path exists.

  7. w+: Open file for reading and writing. The file is created (if it does not exist) or truncated.

  8. wx+: Like 'w+' but fails if path exists.

  9. a: Open file for appending. The file is created if it does not exist.

  10. ax: Like 'a' but fails if the path exists.

  11. a+: Open file for reading and appending. The file is created if it does not exist.

  12. ax+: Like 'a+' but fails if the the path exists.

Example:

Let us create a js file named sample.js having the following code to open a file sample.txt for reading and writing.

var fs = require("fs");

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

Now run the sample.js to see the result:

$ node sample.js

Output.

Going to open file!
File opened successfully!


2. Get File Information


Syntax:

Following is the syntax of the method to get the information about a file −

fs.stat(path, callback)

Parameters:

Here is the description of the parameters used:

  • path: This is the string having file name including path.

  • callback: This is the callback function which gets two arguments (err, stats) where stats is an object of fs.Stats type.


3. Writing a File


Syntax:

Following is the syntax of one of the methods to write into a file −

fs.writeFile(filename, data[, options], callback)

This method will over-write the file if the file already exists. If you want to write into an existing file then you should use another method available.


Parameters:

Here is the description of the parameters used:

  • path: This is the string having the file name including path.

  • data: This is the String or Buffer to be written into the file.

  • options: The third parameter is an object which will hold {encoding, mode, flag}. By default. encoding is utf8, mode is octal value 0666. and flag is 'w'

  • callback: This is the callback function which gets a single parameter err that returns an error in case of any writing error.

Example:

Let us create a js file named sample.js having the code:

var fs = require("fs");

console.log("Going to write into existing file");
fs.writeFile('sample.txt''Simple Easy Learning!'function(err) {
   if (err) {
      return console.error(err);
   }
 
 console.log("Data written successfully!");
 console.log("Let's read newly written data");
 
 fs.readFile('sample.txt'function (err, data) {
      if (err) {
         return console.error(err);
      }
 console.log("Asynchronous read: " + data.toString());
   });
});

Now run the sample.js to see the result:

$ node sample.js

Output.

Going to write into existing file
Data written successfully!
Let's read newly written data
Asynchronous read: Simple Easy Learning!


4. Reading a File


Syntax:

Following is the syntax of one of the methods to read from a file:

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

This method will use file descriptor to read the file. If you want to read the file directly using the file name, then you should use another method available.


Parameters:

Here is the description of the parameters used:

  • fd: This is the file descriptor returned by fs.open().

  • buffer: This is the buffer that the data will be written to.

  • offset: This is the offset in the buffer to start writing at.

  • length: This is an integer specifying the number of bytes to read.

  • position: This is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

  • callback: This is the callback function which gets the three arguments, (err, bytesRead, buffer).


Example:

Let us create a js file named sample.js with the code

var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");
fs.open('sample.txt''r+'function(err, fd) {
   if (err) {
      return console.error(err);
   }
 console.log("File opened successfully!");
 console.log("Going to read the file");
 
 fs.read(fd, buf0, buf.length0function(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());
      }
   });
});

Now run the sample.js to see the result:

$ node sample.js

Output.

Going to open an existing file
File opened successfully!
Going to read the file
97 bytes read
We want to learn Node.js File System in an easy and understandable way!!


5. Closing a File


Syntax:

Following is the syntax to close an opened file:

fs.close(fd, callback)

Parameters:

Here is the description of the parameters used:

  • fd: This is the file descriptor returned by file fs.open() method.

  • callback: This is the callback function No arguments other than a possible exception are given to the completion callback.

Example:

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

var fs = require("fs");
var buf = new Buffer(1024);

console.log("Going to open an existing file");
fs.open('sample.txt''r+'function(err, fd) {
   if (err) {
      return console.error(err);
   }
 console.log("File opened successfully!");
 console.log("Going to read the file");
 
 fs.read(fd, buf0, buf.length0function(err, bytes) {
      if (err) {
 console.log(err);
      }

      // Print only read bytes to avoid junk.
      if(bytes > 0) {
 console.log(buf.slice(0, bytes).toString());
      }

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

Now run the main.js to see the result:

$ node main.js

Output.

Going to open an existing file
File opened successfully!
Going to read the file
We want to learn Node.js File System in an easy and understandable way!!

File closed successfully.


6. Truncate a File


Syntax:

Following is the syntax of the method to truncate an opened file:

fs.ftruncate(fd, len, callback)

Parameters:

Here is the description of the parameters used

  • fd: This is the file descriptor returned by fs.open().

  • len: This is the length of the file after which the file will be truncated.

  • callback: This is the callback function No arguments other than a possible exception are given to the completion callback.


7. Delete a File


Syntax:

Following is the syntax of the method to delete a file:

fs.unlink(path, callback)


Parameters:

Here is the description of the parameters used:

  • path: This is the file name including path.

  • callback: This is the callback function No arguments other than a possible exception are given to the completion callback.




If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com

Node.js, Node.js Assignment, Node.js Assignment Help, Node.js Project, Node.js File System, Node.js Modules, Node.js Examples

9 views0 comments
bottom of page