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

3

6

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.

Highfalutin answered 10/8, 2014 at 14:5 Comment(1)
The fact that you're closing the file in open's callback is kind of strange.Rodi
S
3

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);
};
Sewoll answered 10/8, 2014 at 14:26 Comment(1)
This is incorrect. The line console.log(buffer.toString('utf8')); does not wait for the asynchronous call to fs.read, so it is not guaranteed to work. Testing the code, it often fails and spits out gibberish because the buffer has not had all the file bytes read into it. Any use of buffer needs to happen inside testCallback, although in this case, we have a while loop of calls to fs.read so we need a better way to figure out when all the calls the fs.read have finished.Eldrida
F
0

fs.read and fs.fstat are async functions.

And just after calling, fstat, you are closing the file (fs.close(fd);).

That could be the reason for this error.

Fluorine answered 10/8, 2014 at 14:17 Comment(0)
H
0

The error in the code is that you are currently using asynchronus functions in your application. Which simply means that before performing the first operation the other one starts in parallel i.e. fs.close() closes your file before performing the operation. You can simple replace them with synchronus functions provided by the same fs module from node.js.

Hawley answered 28/1, 2023 at 16:4 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.