Related Articles

Related Articles

Node.js | fsPromises.truncate() Method
  • Last Updated : 23 Jun, 2020

The fsPromises.truncate() method is defined in the File System module of Node.js. The File System module is basically used to interact with the hard-disk of the user’s computer.

The truncate() method is used to modify the inner contents of the file by ‘len’ bytes. If len is shorter than the file’s current length, the file is truncated to that length of len and if it is greater than the file length is padded by appending null bytes (x00) until len is reached.

Syntax:

fs.promises.truncate(path, len)

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

  • path: It is an String, Buffer or Url that specifies the path to the target file.
  • len: It is an numeral value that specifies the length of the file after which file is to be truncated. It is an optional parameter, Default value is 0 i.e. if len parameter is not provided, it will truncated the whole file.

Return Value: This method returns a promise that will be resolved with no argument upon success or rejected with an error object if something went wrong(ex- given path is a path to the directory or given path not exist).



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the   
// fsPromises.truncate() Method
  
// Importing File System module
const fs = require('fs');
  
// Truncate operation
fs.promises.truncate('./test.txt')
  
    // If file is successfully truncated
    .then(() => {
        console.log('File contents are deleted!');
    })
  
    // If any error occurs
    .catch(err => {
        console.log(`Error Occurs, Error code -> 
    ${err.code}, Error NO -> ${err.errno}`)
    });

chevron_right


Implementing the same functionality using async-await.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the   
// fsPromises.truncate() Method
  
// Importing File System module
const fs = require('fs');
  
const truncate = async (path) => {
  
    // Truncate operation
    await fs.promises.truncate(path);
    console.log('File contents are deleted!');
}
  
truncate('./test.txt')
  
    // If any error occurs
    .catch(err => {
        console.log(`Error Occurs, Error code -> 
        ${err.code}, Error NO -> ${err.errno}`)
    });

chevron_right


File contents before running the program:

File contents after running the program:

Output:

File contents are deleted!

Example 2: Truncate partially

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the   
// fsPromises.truncate() Method
  
// Importing File System module
const fs = require('fs')
  
// Fetching contents before truncate 
fs.promises.readFile('./test.txt')
    .then(buff => {
        const oldContents = buff.toString()
        console.log(`\nContents before 
            truncate : \n${oldContents}`)
  
        // Truncate operation
        return fs.promises.truncate('./test.txt', 12)
    })
  
    // If file is successfully truncated
    .then(() => {
        console.log('\nTruncate done!\n')
  
        // Fetching contents after truncate 
        return fs.promises.readFile('./test.txt')
    })
  
    .then(buff => {
        const newContents = buff.toString()
        console.log(`Contents after 
            truncate : \n${newContents}`)
    })
  
    // If any error occurs
    .catch(err => {
        console.log(`Error Occurs, Error code -> 
        ${err.code}, Error NO -> ${err.errno}`)
    });

chevron_right


Implementing the same functionality using async-await

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the   
// fsPromises.truncate() Method
  
// Importing File System module
const fs = require('fs')
  
// Function to read file contents
const readFileContents = async (path) => {
    const buff = await fs.promises.readFile(path)
    return buff.toString()
}
  
// Function to truncate
const truncate = async (path, len) => {
  
    // Fetching contents before truncate 
    const oldContents = 
        await readFileContents('./test.txt')
  
    console.log(`\nContents before 
            truncate : \n${oldContents}`)
  
    // Truncate operation
    const buff = await fs.promises.truncate(path, len)
    console.log('\nTruncate done!\n')
  
    // Fetching contents before truncate 
    const newContents = 
        await readFileContents('./test.txt')
  
    console.log(`Contents after 
        truncate : \n${newContents}`)
}
  
truncate('./test.txt', 12)
  
    // If any error occurs
    .catch(err => {
        console.log(`Error Occurs, Error code -> 
        ${err.code}, Error NO -> ${err.errno}`)
    })

chevron_right


File contents before running the program:

File contents after running the program:

Output:

Reference: https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_fspromises_truncate_path_len




My Personal Notes arrow_drop_up
Recommended Articles
Page :