I have a text file index.txt
with the contents of "01234567890000" (not including the quotes).
var fs = require("fs");
var buffer = Buffer.alloc(1000);
fs.open("index.txt", "r+",(err, fd)=>{
if (err) return err;
fs.read(fd,buffer,0,buffer.length,0,(err, bytesRead,buffer)=>{
if (err) return err;
console.log("Before ftruncate: ", buffer.toString());
fs.ftruncate(fd, 10,(err)=>{
if (err) return err;
fs.read(fd,buffer,0,buffer.length,0,(err)=>{
if (err) return err;
fs.close(fd, err =>{
if(err) return err;
console.log("After ftruncate: ", buffer.toString());
});
});
});
});
});
When I run with node the console.logs show
Before ftruncate: 01234567890000
After ftruncate: 01234567890000
But when I look at the index.txt
is shows: "0123456789" as I expected, but I instead thought the console.logs would look like this:
Before ftruncate: 01234567890000
After ftruncate: 0123456789
To make matters worse when I run:
var buffer = Buffer.alloc(1000);
fs.open("index.txt", "r+",(err, fd)=>{
if (err) return err;
console.log("Before ftruncate: ", buffer.toString());
fs.ftruncate(fd, 10,(err)=>{
if (err) return err;
fs.read(fd,buffer,0,buffer.length,0,(err)=>{
if (err) return err;
fs.close(fd, err =>{
if(err) return err;
console.log("After ftruncate: ", buffer.toString());
});
});
});
});
After reseting the index.txt file, the output is:
Before ftruncate:
After ftruncate: 0123456789
So my question is when I use the console.log
, it shows the ftruncated/new version of the index.txt while other times it doesn't after the ftruncate happens.
(If I had a guess, it would have something to do with mutability. )
(Bonus: It is correct to say that for the 2nd example, for the output of before ftruncate:
, it gives nothing because I didn't run fs.read
which puts the file that you are reading into the buffer?)