Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
How to Add Data in JSON File using Node.js ?
Next article icon

How to truncate a file using Node.js ?

Last Updated : 31 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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 method can be used for either increasing or decreasing the file size. This method changes the length of the file by using the ‘len’ bytes. The ‘len’ represents the content truncated by this length from the file’s current length. If the ‘len’ is greater than the file’s length then the content is appended by null bytes (x00) until the desired length is reached.

Syntax:

fs.truncate( path, len, callback )

Parameters: The method accepts the above parameters that are explained below:

  • path: This parameter holds the path of the target file. This path can either be a string, buffer, or URL.
  • len: This parameter defines the length of the file after which the file will be truncated. This takes an integer input. The default value is 0.
  • callback: This callback accepts one argument that will receive any exception thrown in the call.

Note: In the latest version of Node.js, the callback is not an optional parameter anymore. “Type Error” is thrown when the callback parameter is not defined.

Return Value: This returns the file after truncation.

Example 1: 

Javascript

// Node.js program to demonstrate the
// truncation of File
 
// Importing the fs module
const fs = require('fs');
 
// Truncating all the content of the file
fs.truncate('/path/to/file', 0, function () {
    console.log('File is truncated !!!')
});
                      
                       

Output:

File is truncated !!!

Method 2: The fs.write() method can asynchronously write the specified data to a file. We can use this same property to truncate the file. We can replace all the content with an empty string and all the file content will be truncated.

Syntax:

fs.writeFile( file, data, options, callback )

Parameters: The method accepts the above parameters that are explained below:

  • file: This takes input as String, Buffer, URL, or a file description integer. This integer denotes the path of the file where it will be written.
  • data: This is a String, Buffer, TypedArray, or DataView that will be written to the file.
  • options: This is a String or Object that is used for specifying the optional parameters.
  • callback: This defines the callback function that is called when the method is executed to catch any errors.

Example 2:

Javascript

// Node.js program to demonstrate the
// truncation of file using fs.writeFile() method
 
// Importing the filesystem module
const fs = require('fs');
 
// Replacing the content of the file with empty string
fs.writeFile('/path/to/file', '',
  function(){console.log('File Truncated Successfully !!!')})
                      
                       

Output:

File Truncated Successfully !!!


Next Article
How to Add Data in JSON File using Node.js ?

M

mayank021
Improve
Article Tags :
  • Node.js
  • Web Technologies

Similar Reads

  • How to Update Data in JSON File using Node?
    To update data in JSON file using Node.js, we can use the require module to directly import the JSON file. Updating data in a JSON file involves reading the file and then making the necessary changes to the JSON object and writing the updated data back to the file. Table of Content Using require() M
    4 min read
  • How to Download a File Using Node.js?
    Downloading files from the internet is a common task in many Node.js applications, whether it's fetching images, videos, documents, or any other type of file. In this article, we'll explore various methods for downloading files using Node.js, ranging from built-in modules to external libraries. Usin
    3 min read
  • How to read and write JSON file using Node ?
    Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises. JSON(JavaScript Object Notation) is a simple and
    3 min read
  • How To Read a File Line By Line Using Node.js?
    To read a file line by line in Node.js, there are several approaches that efficiently handle large files and minimize memory usage. In this article, we'll explore two popular approaches: using the Readline module (which is built into Node.js) and using the Line-reader module, a third-party package.
    3 min read
  • How to Add Data in JSON File using Node.js ?
    JSON stands for Javascript Object Notation. It is one of the easiest ways to exchange information between applications and is generally used by websites/APIs to communicate. For getting started with Node.js, refer this article. Prerequisites:NPM NodeApproachTo add data in JSON file using the node js
    4 min read
  • How to read and write files in Node JS ?
    NodeJS provides built-in modules for reading and writing files, allowing developers to interact with the file system asynchronously. These modules, namely fs (File System), offer various methods for performing file operations such as reading from files, writing to files, and manipulating file metada
    2 min read
  • How to create a RAM disk using Node.js ?
    A RAM disk is a virtual disk device that stores data on a portion of a computer's RAM. It has faster read and write speeds than conventional hard drives or solid-state drives because data can be accessed and written to and from RAM much faster. We'll look at how to make a RAM disk with Node.js, a po
    3 min read
  • How to add authentication in file uploads using Node.js ?
    There are multiple ways to upload files and apply authentications to them. The easiest way to do so is to use a node module called multer. We can add authentication by restricting users on file uploads such as they can upload only pdf and the file size should be less than 1 Mb. There are many module
    3 min read
  • How to Copy a File in Node.js?
    Node.js, with its robust file system (fs) module, offers several methods to copy files. Whether you're building a command-line tool, a web server, or a desktop application, understanding how to copy files is essential. This article will explore various ways to copy a file in Node.js, catering to bot
    2 min read
  • How to work with Node.js and JSON file ?
    Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences