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.
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.
File contents before running the program:
File contents after running the program:
Truncate done, File contents are deleted!
Example 2: This example illustrates how to truncate works, when length after file will be truncated, is given.