The Wayback Machine - https://web.archive.org/web/20240908231326/https://www.geeksforgeeks.org/node-js-fs-truncate-method/
Open In App

Node.js fs.truncate() Method

Last Updated : 12 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The fs.truncate() method in node.js is used to change the size of the file i.e either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file’s current length, the file is truncated to that length. If it is greater than the file length is padded by appending null bytes (x00) until len is reached.

Syntax:

fs.truncate( path, len, callback )

Parameters: This method accept three parameters as mentioned above and described below:

  • path: It holds the path of targeted file. It can be either string, buffer or a url.
  • len: It holds the length of the file after which the file will be truncated. It takes an integer input and it is not the mandatory condition as it is default set to 0.
  • callback: The callback receives one argument, any exception throws in the call.

Note: In latest version of node.js, callback is no longer optional parameter. If we will not use the callback parameter then it will return “Type Error” on run-time.

Return Value: It changes the length of the desired file to the desired length.

Example 1:




// Node.js program to demonstrate the
// fs.truncate() method
   
// Include the fs module
var fs = require('fs');
  
// Completely delete the content
// of the targeted file
fs.truncate('/path/to/file', 0, function() {
    console.log('File Content Deleted')
});


Output:

File Content Deleted

Example 2:




// Node.js program to demonstrate the
// fs.truncate() method
   
// Include the fs module
var fs = require('fs');
  
console.log("Content of file");
   
// Opening file
fs.open('input.txt', 'r+', function(err, fd) {
    if (err) {
        return console.error(err);
    }
   
    // Reading file
    fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
        if (err){
            console.log(err);
        }
   
        // Truncating the file
        fs.truncate('/path/to/file', 15, function(err, bytes){
            if (err){
                console.log(err);
            }
   
            // Content after truncating
            console.log("New content of file");
            fs.read(fd, buf, 0, buf.length, 0, function(err, bytes){
                if (err) {
                    console.log(err);
                }
                  
                // Print only read bytes to avoid junk.
                if(bytes > 0) {
                    console.log(buf.slice(0, bytes).toString());
                }
   
                // Close the opened file.
                fs.close(fd, function(err) {
                    if (err) {
                        console.log(err);
                    }
                });
            });
        });
    });
});


Output:

Content of file
GeeksforGeeks example for truncate in node
New content of file
GeeksforGeeks

Reference: https://nodejs.org/api/fs.html#fs_fs_ftruncate_fd_len_callback



Previous Article
Next Article

Similar Reads

Node.js fsPromises.truncate() Method
The fsPromises.truncate() method in node.js is used to change the size of the file i.e. either increase or decrease the file size. This method changes the length of the file at the path by len bytes. If len represents a length shorter than the file’s current length, the file is truncated to that length. If it is greater than the file length is padd
2 min read
Node.js fsPromises.truncate() Method
The fsPromises.truncate() method is defined in the File System module of Node.js. The File System module is basically used 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 lengt
3 min read
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
3 min read
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
4 min read
Node.js fs.filehandle.truncate() Method
The fs.filehandle.truncate() method is an inbuilt application programming interface of class fs.filehandle within File System module which is used to truncate the particular file object and only that much byte will be retained which passed as an integer in truncate() method. Syntax: const filehandle.truncate(len) Parameter: This method takes the le
3 min read
How to truncate a file using Node.js ?
In this article, we are going to explore How to truncate the complete file using Node. There are two methods to truncate the file of all its data. We can either use the fs.truncate() method or the fs.writeFile() method to replace all the file content. Method 1: The fs.truncate() method in Node.js can be used for changing the file size, i.e. this me
3 min read
Lodash _.truncate() Method
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.truncate() method of String in lodash is used to truncate the stated string if it is longer than the specified string length. The last characters of the string which are truncated are replaced with the st
2 min read
How to truncate text in Angular2?
Approach: It is easy to truncate text in Angular. The truncated text helps us to remove or cut-off portions of text. It abruptly ends the text, reducing the length of the text. It removes text in accordance with the truncate function used. Syntax: String length is greater than the given characters. function(str, length, ending) {........} String tr
2 min read
Truncate a String using filter in Vue.js
In this article, we are going to learn how to truncate strings using filters in VueJS. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns a
2 min read
Primer CSS Truncate Expand on Hover or Focus
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
3 min read
Primer CSS Truncate Custom Max Widths
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by Object-Oriented CSS principles, functional CSS, an
3 min read
Primer CSS Truncate
Primer CSS is a CSS framework that comes with pre-styled components and a design language with spacing, typography, and Theming that helps in building a website effectively. This systematic method makes sure our patterns are steady and interoperable with every other. It is created with GitHub’s design system. Primer CSS truncate is used to shorten
2 min read
Primer CSS Truncate Multiple Items
Primer CSS is a free open-source CSS framework that is built upon systems that create the foundation of the basic style elements such as spacing, typography, and color. This systematic method makes sure our patterns are steady and interoperable with every other. Its approach to CSS is influenced by object-oriented CSS principles, functional CSS, an
2 min read
How to truncate the text using Angular Pipe and Slice ?
Angular Pipe and Slice can be used to manipulate or transform the data in a specific format. Angular Pipes can be utilized to format or transform data directly before displaying it in the Angular template. The Slice is a built-in method in JavaScript that enables the users to extract a part of the array or string without modifying the original data
3 min read
JavaScript Program to Truncate a String to a Certain Length and Add Ellipsis (...)
In this article, we will see how to truncate a string to a certain length and add an ellipsis (...) in JavaScript. To truncate a string to a specific length and add an ellipsis (...) in JavaScript means shortening the string to a predefined character count, indicating that the content continues beyond the truncated portion. There are several method
3 min read
JavaScript Program to Truncate a String to a Certain Length
In this article, we are going to learn how can we truncate a string to a certain length. Truncating a string to a certain length in JavaScript means shortening a string so that it doesn't exceed a specified maximum length. This can be useful for displaying text in user interfaces, such as titles or descriptions while ensuring that the text does not
3 min read
How to Truncate a String in JavaScript ?
In JavaScript, there are several ways to truncate a string which means cutting off a part of the string to limit its length. Truncating a string is useful when we want to display only a certain number of the characters in the user interfaces such as previewing a longer text or ensuring that text fits within the specified space. Use the below method
2 min read
How to truncate an array in JavaScript ?
In JavaScript, there are two ways of truncating an array. One of them is using length property and the other one is using splice() method. In this article, we will see, how we can truncate an array in JavaScript using these methods. These are the following ways to truncate an array: Table of Content Using length PropertyUsing splice() MethodUsing s
5 min read
Node.js Http2ServerRequest.method Method
The Http2ServerRequest.method is an inbuilt application programming interface of class Http2ServerRequest within the http2 module which is used to get the string representation of the request method. Syntax: const request.method Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the string represe
3 min read
Node.js http.IncomingMessage.method Method
The http.IncomingMessage.method is an inbuilt application programming interface of class Incoming Message within the inbuilt http module which is used to get the type of request method as a string. Syntax: request.method Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the request type name as a
2 min read
Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic
2 min read
How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
Encountering the error message ‘node’ is not recognized as an internal or external command after installing Node.js can be frustrating, especially when you’re eager to start working on your project. This error usually means that your system cannot find the Node.js executable because the path to it is not set correctly in your system's environment v
2 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
5 min read
Node.js URLSearchParams.has() Method
In URLSearchParams interface, the has() method returns a Boolean which tells us that if the parameter with input name exists it will return true, else false. Syntax: var Bool = URLSearchParams.has(name) Returns: True - if name present, else it will return False. Parameters: name - Input the name of the parameter. Example1: let url = new URL('https:
1 min read
Node.js hmac.update() Method
The hmac.update() method is an inbuilt method of class HMAC within the crypto module which is used to update the data of hmac object. Syntax: hmac.update(data[, inputEncoding])Parameters: This method takes the following two parameters: data: It can be of string, Buffer, TypedArray, or DataView type. It is the data that is passed to this function.in
2 min read
Node.js process.send() Method
The process.send() method is an inbuilt application programming interface of the process module which is used by the child process to communicate with the parent process. This method does not work for the root process because it does not have any parent process. Syntax: process.send(message, [sendHandle])Parameters: This method accepts the followin
2 min read
Node.js writeStream.clearLine() Method
The writeStream.clearLine() is an inbuilt application programming interface of class WriteStream within the module which is used to clear the current line of this write stream object. Syntax: writeStream.clearLine(dir[, callback]) Parameters: This method takes the following argument as a parameter: dir: Integer value defining the selection of a lin
2 min read