How to operate callback-based fs.truncate() method with promises in Node.js ?

The fs.truncate() method 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 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.

The fs.truncate() method is based on callback. Using callback methods leads to a great chance of callback nesting or callback hell problems. Thus to avoid it we almost always like to work with a promise-based method. Using some extra node.js methods we can operate a callback-based method in promise way.

Syntax:

fs.truncate(path, len)

Note: Callback not required since we operate the method with promises.

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: If method operates with promises 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).

Approach: The fs.truncate() method based on callback. To operate it with promises, first, we use promisify() method defined in the utilities module to convert it into a promise based method.

Example 1:
Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to 
// promise based methods
const trunct = util.promisify(fs.truncate)
   
// The truncate operation
trunct('./testFile.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

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to
// promise based methods
const trunct = util.promisify(fs.truncate)
   
const truncateFile = async (path) => {
  
  // The truncate operation
  await trunct(path)
  console.log('File contents are deleted!')
}
   
truncateFile('./testFile.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:

Run the index.js file using the following command:

node index.js

Output:

File contents are deleted!

Example 2:
Filename: index.js

filter_none

edit
close

play_arrow

link
brightness_4
code

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods to 
// promise based methods
const trunct = util.promisify(fs.truncate)
const readFileContent = util.promisify(fs.readFile)
   
// Fetching contents before truncate 
readFileContent('./testFile.txt')
.then(buff => {
  const oldContents = buff.toString()
  console.log(`\nContents before 
      truncate : \n${oldContents}`)
   
  // The truncate operation
  return trunct('./testFile.txt', 18)
})
   
// If file is successfully truncated
.then(() => {
  console.log('\nTruncate done!\n')
   
  // Fetching contents after truncate 
  return readFileContent('./testFile.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

// Importing File System and Utilities module
const fs = require('fs')
const util = require('util')
  
// Convert callback based methods 
// to promise based methods
const trunct = util.promisify(fs.truncate)
const readFileContent = util.promisify(fs.readFile)
   
// Function to fetch file contents
const fetchFileContents = async (path) => {
  const buff = await readFileContent(path)
  return buff.toString()
}
   
// Function to truncate
const truncateFile = async (path, len) => {
     
  // Fetching contents before truncate 
  const oldContents = await fetchFileContents(path)
  console.log(`\nContents before 
    truncate : \n${oldContents}`)
     
  // The truncate operation
  const buff = await trunct(path, len)
  console.log('\nTruncate done!\n')
   
  // Fetching contents before truncate 
  const newContents = await fetchFileContents(path)
  console.log(`Contents after 
    truncate : \n${newContents}`)
}
   
truncateFile('./testFile.txt', 18)
  
// If any error occurs
.catch(err => {
   console.log(`Error Occurs, 
   Error code -> ${err.code}, 
   Error NO -> ${err.errno}`);
})

chevron_right


Run the index.js file using the following command:

node index.js

File contents before running the program:

File contents after running the program:

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.