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
const fs = require( 'fs' )
const util = require( 'util' )
const trunct = util.promisify(fs.truncate)
trunct( './testFile.txt' )
.then(() => {
console.log( 'File contents are deleted!' )
})
. catch (err => {
console.log(`Error Occurs,
Error code -> ${err.code},
Error NO -> ${err.errno}`);
});
|
Implementing the same functionality using async-await.
const fs = require( 'fs' )
const util = require( 'util' )
const trunct = util.promisify(fs.truncate)
const truncateFile = async (path) => {
await trunct(path)
console.log( 'File contents are deleted!' )
}
truncateFile( './testFile.txt' )
. 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
const fs = require( 'fs' )
const util = require( 'util' )
const trunct = util.promisify(fs.truncate)
const readFileContent = util.promisify(fs.readFile)
readFileContent( './testFile.txt' )
.then(buff => {
const oldContents = buff.toString()
console.log(`\nContents before
truncate : \n${oldContents}`)
return trunct( './testFile.txt' , 18)
})
.then(() => {
console.log( '\nTruncate done!\n' )
return readFileContent( './testFile.txt' )
})
.then(buff => {
const newContents = buff.toString()
console.log(`Contents after
truncate : \n${newContents}`)
})
. catch (err => {
console.log(`Error Occurs,
Error code -> ${err.code},
Error NO -> ${err.errno}`);
});
|
Implementing the same functionality using async-await.
const fs = require( 'fs' )
const util = require( 'util' )
const trunct = util.promisify(fs.truncate)
const readFileContent = util.promisify(fs.readFile)
const fetchFileContents = async (path) => {
const buff = await readFileContent(path)
return buff.toString()
}
const truncateFile = async (path, len) => {
const oldContents = await fetchFileContents(path)
console.log(`\nContents before
truncate : \n${oldContents}`)
const buff = await trunct(path, len)
console.log( '\nTruncate done!\n' )
const newContents = await fetchFileContents(path)
console.log(`Contents after
truncate : \n${newContents}`)
}
truncateFile( './testFile.txt' , 18)
. 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:
Last Updated :
18 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...