Di Wu
Di Wu

Reputation: 19

Variable got cleared unexpectly

I am implementing a function to read contents in local foo.txt.

var fs = require("fs");
var path = require("path");

var realpath = path.resolve("./foo.txt");

fs.open(realpath, "r", function(err, fd){
    if ( err ) { throw err; };
    var buf = new Buffer(1024),
    bufOffset = 0,
    bufLength = buf.length,
    result = "";

    var recursive = function(position) {
        buf = new Buffer(1024)
        fs.read(fd, 
                buf,
                bufOffset,
                bufLength,
                position,
                function(err, bytesRead, buffer) {
                    if ( err ) { throw new Error("Opps!"); };
                    if (bytesRead > 0) { // Block**
                        result = result.concat( buffer.slice(0, bytesRead).toString() );
                        recursive(bytesRead + position);
                    }
                });
    };

    recursive(0);
    console.log(result);
});

I used recursive method. After executing this program I got nothing. But if I use console.log(result) in the Block** above, it works. Why result gets cleaned after the program went back to the open block? thanks.

Upvotes: 0

Views: 45

Answers (1)

Aesthete
Aesthete

Reputation: 18850

Due to the asynchronous nature of read method, the result variable has not been populated by the time you print it. That's the point of supplying a callback for completion.

Upvotes: 1

Related Questions