Open In App

Node.js fsPromises.truncate() Method

The fsPromises.truncate() method in node.js is used to change the size of the file i.e. either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file’s current length, the file is truncated to that length. If it is greater than the file length is padded by appending null bytes (x00) until len is reached.

It then resolves the Promise with no arguments upon success. The path must be a String or Buffer.

Syntax:



fsPromises.truncate( path, len )

Parameters: This method accepts two parameters as mentioned above and described below:

Return Value: This method returns the Promise.



Example: This example illustrates the working of fsPromises.truncate() method in Node.js:

Create a Hello.txt file in the current root directory with some sample text as shown below: 

Greetings from GeeksforGeeks

Filename: index.js 




// Node.js program to demonstrate the
// fsPromises.truncate() method
    
// Include the fs module
const fs = require('fs');
const fsPromises = fs.promises;
 
fsPromises.truncate('Hello.txt', 0)
.then(function() {
    console.log("File Content Deleted");
})
.catch(function(error) {
    console.log("Error",error);
});

Step to run this program: Run the index.js file using the following command: 

node index.js

Output: 

File Content Deleted

Reference: https://nodejs.org/api/fs.html#fs_fspromises_truncate_path_len

Article Tags :