Node.js filehandle.truncate() Method

The filehandle.truncate() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The truncate() method 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:

filehandle.truncate( len );

Parameter: This method accepts single parameter as mentioned above and described below:

  • 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: It returns a promise which 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: This example illustrates how to truncate works when length after file will be truncated is not given.



filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and 
// Utilities module
const fs = require('fs')
  
const truncateFile = async (path) => {
    let filehandle = null
  
    try {
        filehandle = await fs.promises
                .open(path, mode = 'r+')
        // Append operation
        await filehandle.truncate()
        console.log('\nTruncate done, File"
                + " contents are deleted!\n')
    } finally {
        if (filehandle) {
  
            // Close the file if it is opened.
            await filehandle.close();
        }
    }
}
  
truncateFile('./testFile.txt')
    .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:

Truncate done, File contents are deleted!

Example 2: This example illustrates how to truncate works, when length after file will be truncated, is given.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
  
// fs.readFileSync(() method reads the file
// and returns buffer form of the data 
const oldBuff = fs.readFileSync('./testFile.txt')
  
// File content after append 
const oldContent = oldBuff.toString()
console.log(`\nContents before truncate :
                         \n${oldContent}`)
  
const truncateFile = async (path, len) => {
    let filehandle = null
  
    try {
        filehandle = await fs.promises
                .open(path, mode = 'r+')
        // Append operation
        await filehandle.truncate(len)
        console.log('\nTruncate done!\n')
    } finally {
        if (filehandle) {
  
            // Close the file if it is opened.
            await filehandle.close();
        }
    }
  
    const newBuff = fs.readFileSync(path)
    //File content after truncate
    const newContent = newBuff.toString()
    console.log(`Contents after truncate :
                        \n${newContent}`)
}
  
truncateFile('./testFile.txt', 52)
    .catch(err => {
        console.log(`Error Occurs, Error code -> 
            ${err.code}, Error NO -> ${err.errno}`)
    })

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.