Open In App

Node.js fs.ftruncate() Method

The fs.ftruncate() method is used to change the size of the file i.e. either increase or decrease the file size. It changes the length of the file at the path by len bytes. If len is shorter than the file’s current length, the file is truncated to that length. If it is greater than the file length, it is padded by appending null bytes (x00) until len is reached. It is similar to the truncate() method, except it accepts a file descriptor of the file to truncate.

Syntax:



fs.ftruncate(fd, len, callback)

Parameters: This method accept three parameters as mentioned above and described below:

Below examples illustrate the fs.ftruncate() method in Node.js:



Example 1:




// Node.js program to demonstrate the
// fs.ftruncate() method
  
// Import the filesystem module
const fs = require('fs');
  
console.log("Contents of file before truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));
  
// Get the file descriptor of the file
const fd = fs.openSync('example_file.txt', 'r+');
  
fs.ftruncate(fd, 24, (err) => {
  if (err)
    console.log(err)
  else {
    console.log("Contents of file after truncate:")
    console.log(fs.readFileSync('example_file.txt', 'utf8'));
  }
});

Output:

Contents of file before truncate:
This is an example file for the ftruncate() method.
Contents of file after truncate:
This is an example file

Example 2:




// Node.js program to demonstrate the
// fs.ftruncate() method
  
// Import the filesystem module
const fs = require('fs');
  
console.log("Contents of file before truncate:")
console.log(fs.readFileSync('example_file.txt', 'utf8'));
  
// get the file descriptor of the file
const fd = fs.openSync('example_file.txt', 'r+');
  
// Truncate the whole file
fs.ftruncate(fd, (err) => {
  if (err)
    console.log(err)
  else {
    console.log("Contents of file after truncate:")
    console.log(fs.readFileSync('example_file.txt', 'utf8'));
  }
});

Output:

Contents of file before truncate:
This is an example file for the ftruncate() method.
Contents of file after truncate:

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


Article Tags :