Open In App

How to truncate a file using Node.js ?

In this article, we are going to explore How to truncate the complete file using Node. There are two methods to truncate the file of all its data. We can either use the fs.truncate() method or the fs.writeFile() method to replace all the file content.

Method 1: The fs.truncate() method in Node.js can be used for changing the file size, i.e. this method can be used for either increasing or decreasing the file size. This method changes the length of the file by using the ‘len’ bytes. The ‘len’ represents the content truncated by this length from the file’s current length. If the ‘len’ is greater than the file’s length then the content is appended by null bytes (x00) until the desired length is reached.



Syntax:

fs.truncate( path, len, callback )

Parameters: The method accepts the above parameters that are explained below:



Note: In the latest version of Node.js, the callback is not an optional parameter anymore. “Type Error” is thrown when the callback parameter is not defined.

Return Value: This returns the file after truncation.

Example 1: 




// Node.js program to demonstrate the
// truncation of File
 
// Importing the fs module
const fs = require('fs');
 
// Truncating all the content of the file
fs.truncate('/path/to/file', 0, function () {
    console.log('File is truncated !!!')
});

Output:

File is truncated !!!

Method 2: The fs.write() method can asynchronously write the specified data to a file. We can use this same property to truncate the file. We can replace all the content with an empty string and all the file content will be truncated.

Syntax:

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

Parameters: The method accepts the above parameters that are explained below:

Example 2:




// Node.js program to demonstrate the
// truncation of file using fs.writeFile() method
 
// Importing the filesystem module
const fs = require('fs');
 
// Replacing the content of the file with empty string
fs.writeFile('/path/to/file', '',
  function(){console.log('File Truncated Successfully !!!')})

Output:

File Truncated Successfully !!!

Article Tags :