Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use fs.read() in Node js

I try to use Nodejs fs.read Method in Mac OS. However it doesn't work.. I use below source code

    var fs = require('fs');
    fs.open('helloworld.txt', 'r', function(err, fd) {
        fs.fstat(fd, function(err, stats) {

            var bufferSize=stats.size  ,
                chunkSize=512,
                buffer=new Buffer(bufferSize),
                bytesRead = 0;

            while (bytesRead < bufferSize) {
                if ((bytesRead + chunkSize) > bufferSize) {
                    chunkSize = (bufferSize - bytesRead);
                }

                fs.read(fd, buffer, bytesRead, chunkSize, bytesRead, testCallback);
                bytesRead += chunkSize;
            }
            console.log(buffer.toString('utf8'));
        });
        fs.close(fd);
    });

    var testCallback = function(err, bytesRead, buffer){
        console.log('err : ' +  err);
    };

Actually, I use some example in stackoverflow.

When I execute the source,

err : Error: EBADF, read

this err is returned.

However if I use readFile method, it works well.

    fs.readFile('helloworld.txt', function (err, data) {
       if (err) throw err;    
       console.log(data.toString('utf8'));
    });

result is

Hello World!

Of course, it's same file.

Please, let me know what the problem is.

Thank you.

like image 668
Kang Hyuk Suh Avatar asked Oct 20 '22 03:10

Kang Hyuk Suh


1 Answers

The difference is not int the functions you are using, but in the way you are using them.

All those fs.* functions you are using are asynchronous, that means they run in parallel. So, when you run fs.close, the others have not finished yet.

You should close it inside the fs.stat block:

var fs = require('fs');
fs.open('helloworld.txt', 'r', function(err, fd) {
    fs.fstat(fd, function(err, stats) {

        var bufferSize=stats.size  ,
            chunkSize=512,
            buffer=new Buffer(bufferSize),
            bytesRead = 0;

        while (bytesRead < bufferSize) {
            if ((bytesRead + chunkSize) > bufferSize) {
                chunkSize = (bufferSize - bytesRead);
            }

            fs.read(fd, buffer, bytesRead, chunkSize, bytesRead, testCallback);
            bytesRead += chunkSize;
        }
        console.log(buffer.toString('utf8'));
        fs.close(fd);
    });
});

var testCallback = function(err, bytesRead, buffer){
    console.log('err : ' +  err);
};
like image 57
Nuno Barreto Avatar answered Oct 31 '22 18:10

Nuno Barreto