How to operate callback-based fs.truncate() method with promises in Node.js ?
Last Updated :
18 Jul, 2020
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
javascript
// 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}`);
});
Implementing the same functionality using async-await.
javascript
// 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}`);
});
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
javascript
// 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}`);
});
Implementing the same functionality using async-await.
javascript
// 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}`);
})
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:
Similar Reads
How to operate callback-based fs.rename() method with promises in Node.js ? The fs.rename() method is defined in the File System module of Node.js. The File System module is basically to interact with hard-disk of the userâs computer. The rename() method is used to rename the file at the given old path to a given new path. If the new path file already exists, it will be ove
5 min read
How to operate callback-based fs.readdir() method with promises in Node.js ? The fs.readdir() 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 readdir() method is used to read the contents of a directory. The fs.readdir() method is based on callback. Using callback methods l
3 min read
How to operate callback-based fs.mkdir() method with promises in Node.js ? The fs.mkdir() 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 mkdir() method is used to asynchronously create a directory. The fs.mkdir() method is based on callback. Using callback methods leads
4 min read
How to operate callback-based fs.readFile() method with promises in Node.js ? The fs.readFile() 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 readFile() method is used to asynchronously read the entire contents of a file and returns the buffer form of the data. The fs.read
5 min read
How to operate callback based fs.writeFile() method with promises in Node.js ? The fs.writeFile() is a 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 fs.writeFile() method asynchronously writes data to a file, replacing the file if it already exists. The fs.writeFile() method i
5 min read
How to operate callback-based fs.opendir() method with promises in Node.js ? The fs.opendir() 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 method used to asynchronously open a directory.The fs.opendir() method is based on callback. Using callback methods leads to a great
5 min read
How to operate callback based fs.appendFile() method with promises in Node.js ? The fs.appendFile() 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 appendFile() method is used to append new data in the existing file or if the file does not exist then the file is created first
4 min read
How to convert function call with two callbacks promise in Node.js ? Promise: Promise is used to handle the result, if it gets the required output then it executes the code of then block, and if it gets the error then it executes the code of the catch block.A promise looks like this -function() .then(data => { // After promise is fulfilled console.log(data); }) .c
2 min read
How to Convert an Existing Callback to a Promise in Node.js ? Node.js, by nature, uses an asynchronous, non-blocking I/O model, which often involves the use of callbacks. While callbacks are effective, they can lead to complex and hard-to-read code, especially in cases of nested callbacks, commonly known as "callback hell." Promises provide a cleaner, more rea
7 min read
Which is first argument typically passed to a Node.js callback handler ? A callback handler function in Node.js is a way to handle something after a particular operation is completed. It is one of the ways to handle asynchronous code which takes a long time to yield the result so we can call the callback handler with the error if any, and the result of the asynchronous o
3 min read