InterviewSolution
Saved Bookmarks
| 1. |
what are the steps for truncating a file? |
|
Answer» import fs module and declare buffer class
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
|
|