Learn How to Handle System Files in Node.JS

0
3894
Handle System Files

In the last article, we discussed the concept of streams in Node.js. In this article, we are going to discuss about file handling in node.js and the various operations on the file system along with the suitable examples.

Introduction to Node File System
In Node.js, we use the simple wrappers around standard POSIX functions in order to implement file I/O operations. The following is the syntax to import node file system module (fs).

Asynchronous vs Synchronous in Node.js File System module
In node.js file system (fs) module, every method has asynchronous as well as synchronous forms. In case of asynchronous forms, the first parameter is error and the last parameter is the completion callback function. It is advisable to use asynchronous method over synchronous method as the former never blocks a program while execution, but the latter does. Let us understand it with the help of the following example.

Step 1: – Create a file ‘inputData.txt’ inside the project ‘NodeFileSystemApplication’ with the following text details.

Step 2: – Write the following code in the file ‘index.js. This example is demonstrating an asynchronous as well as a synchronous read for comparison.

Step 3: – After execution of the above program, we can observe the following output. Here, we can observe that the synchronous read is first displayed on the console followed by the asynchronous read as the former blocks a program while execution but the latter never blocks a program.

File operations in Node.js File System
Similar to the other programming languages, Node.js also perform the following file operations.

  • Open a file
  • Get file status and information
  • Write a file
  • Read a file
  • Close a file
  • Delete a file

Open a file in Node.js

We have to first import the ‘fs’ module and use the following method of the instance variable to open a file in an asynchronous mode.

Description of the parameters

  • path – this parameter represents the complete file path with type as string, which includes the path and the file name.
  • flags – this parameter indicates the behavior of the file that to be opened. The following are the possible values.

Flags

Description

r

This flag opens file for reading. It will throw an exception when the file does not exist.

r+

This flag opens file for reading and writing. It will throw an exception when the file does not exist.

rs

This flag opens file for reading in synchronous mode.

rs+

This flag opens file for reading and writing, asking the OS to open it synchronously.

w

This flag opens file for writing. It will create a file if it does not exist or truncated if the file exists.

wx

It is similar as that of flag ‘w’ but fails if the path exists.

w+

This flag opens a file for reading and writing. It will create a file if it does not exist or truncated if the file exists.

wx+

It is similar as that of flag ‘w+’ but fails if path exists.

a

This flag opens file for appending. It will create a file if it does not exist.

ax

It is similar as that of flag ‘a’ but fails if the path exists.

a+

This flag opens file for reading and appending. It will create a file if it does not exist.

  • mode – This parameter is used to set the file mode. It sets the permission and the sticky bits when the file is created. It default values are 0666, readable and writeable.
  • callback – This parameter represents the callback function which accepts the two arguments i.e. (error, data).

Example: – In the following example, we are going to open a file ‘newfile.txt’ for reading and writing.

Output
When we execute the above program, it will open the file in r+ mode and display the following on the console.

Get file status and information
We have to first import the ‘fs’ module and use the following method of the instance variable to procure the information about a file.

Description of the parameters

  • path – This parameter represents the complete file path with type as string which includes the path and the file name.
  • callback − It is the callback function which accepts the two arguments i.e. (error, stats) where stats is an object of fs.Stats type. It has the following useful methods which can be used to check file type.

Method

Description

stats.isFile()

This method returns true if file type of a simple file.

stats.isDirectory()

This method returns true if file type of a directory.

stats.isBlockDevice()

This method returns true if file type of a block device.

stats.isCharacterDevice()

This method returns true if file type of a character device.

stats.isSymbolicLink()

This method returns true if file type of a symbolic link.

stats.isFIFO()

This method returns true if file type of a FIFO.

stats.isSocket()

This method returns true if file type of a socket.

Example: – In the following example, we are going to retrieve information about the file ‘inputData.txt’.

Output
When we execute the above program, it will retrieve the file information and display them on the console.

Writing data to a file in Node.js
We have to first import the ‘fs’ module and use the following method of the instance variable to write data to a file. This method will over-write the file if the file already exists.

Description of the parameters

  • path − This parameter represents the complete file path with type as string which includes the path and the file name.
  • data – This parameter represents the actual data in the type of String or Buffer to be written into the file.
  • options – The options parameter is an object that holds details about encoding, mode, and flag. By default the values of encoding is utf8, mode is octal value 0666, and flag is ‘w’.
  • callback − It is the callback function, which accepts a single parameter error that returns an error when any writing error is encountered.

Reading data from a file in Node.js
We have to first import the ‘fs’ module and use the following method of the instance variable to read the data from a file.

Description of the parameters

  • fd – This parameter is the file descriptor which is returned by filesystem.open() method.
  • buffer − This parameter is the buffer where the data will be written to.
  • offset − This parameter is the offset in the buffer that defines where to start writing.
  • length – This parameter is an integer that specifies the number of bytes which is to be read.
  • position – This parameter is an integer that specifies where to begin reading from in the file. If position is null, then the data will be read from the current file position.
  • callback − This parameter is the callback function which accepts the following three arguments. They are error, bytesRead, and buffer.

Example: – In the following example, we are going to write data to the file ‘inputNewData.txt’ and read this file data by using two read methods i.e. readFile and read.

Output
When we execute the above program, it will read the file data and display them on the console as shown below.

Closing a file in Node.js
We have to first import the ‘fs’ module and use the following method of the instance variable to close a file.

Description of the parameters

  • fd − This parameter represents the file descriptor which is returned by filesystem.open() method.
  • callback − This parameter represents a callback function, which accepts a single error argument to return the error details in case of an exception.

Example: –In the following example, we are going to retrieve information about the file ‘inputData.txt’.

Output
When we execute the above program, it will first open an existing file and then close that file.

Delete a file in Node.js
We have to first import the ‘fs’ module and use the following method of the instance variable to close a file.

Description of the parameters

  • path − This parameter represents the complete file path with type as string, which includes the path and the file name.
  • callback − This parameter represents a callback function which accepts a single error argument to return the error details in case of an exception.

Example: – In the following example, we are going to delete a file ‘output.txt’.

Output
When we execute the above program, it will delete an existing file.

Conclusion: –
In this article, we discussed about the file system in Node.js. Here, we have covered various file handling operations such as opening a file, reading the file status information, write and read file operations, closing a file and deleting a file in Node.js.

LEAVE A REPLY

Please enter your comment!
Please enter your name here