Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

javascript - Using fs.read and fs.ftruncate for node.js

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?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...