1.

what are the steps for truncating a file?

Answer»

import fs module and declare buffer class

  1. Open the file using fs.open method
  2. Execute the method ftruncate to truncate the opened file. PROVIDE the name of the opened file , length of file after which the file will be TRUNCATED.
  3. Read the truncated file after successful truncation using fs.read method and buffer
  4. iclose the file using fs.close method

Example: Create a TEXT file named trnk.txt with Knowledgehut tutorials as text in it

Create a javascript code as follows. Save it as trnkexmpl.js

VAR fs = require("fs"); //import module var buf = new Buffer(1024); //define buffer   fs.open('trnk.txt', 'r+', function (err,fd) { if (err) { return console.error(err); } console.log("File opened"); //Truncate the open file) fs.ftruncate(fd, 12, function(err) { if (err) { return console.log(err); } console.log("File Truncated") console.log("Going to read same file")  fs.read(fd, buf, 0, buf.length, 0 ,function(err, bytes) { if(err) { return console.log(err);  } //PRINT only read bytes if(bytes > 0) { console.log(buf.slice(0, bytes).toString()); }   //Close the opened file fs.close(fd, function(err){ if (err) { console.log(err); } console.log("File closed successfully"); }); }); });   });  

Execute the code . You get the following result

  • File opened
  • File Truncated
  • Going to read same file
  • Knowledgehut
  • File closed successfully


Discussion

No Comment Found