node.js fs.read() example

后端 未结 4 1749
逝去的感伤
逝去的感伤 2020-12-17 15:41
app=function(req,res)
{
 res.writeHead(200,{\'Content-Type\':\'text/plain\'})
 var buffer=new Buffer(100)
 var fs=require(\'fs\')
 fs.open(\'.\'+req.url,\'r\',functi         


        
相关标签:
4条回答
  • 2020-12-17 15:46

    I used the @user1256169 example from above to create what I needed. Here I'm using async.whilst to handle the async control flow more cleanly. At the top of the example I'm reading the file and its stats synchronously, but that can be changed if there is a need to.

    var fs = require('fs');
    var async = require('async');
    
    var fd = fs.openSync('/path/to/cat.png', 'r');
    var stats = fs.fstatSync(fd);
    
    
    var bufferSize = stats.size,
        chunkSize = 512,//bytes
        buffer = new Buffer(bufferSize),
        bytesRead = 0;
    
    async.whilst(
        function () {
            return bytesRead < bufferSize;
        },
        function (done) {
            if ((bytesRead + chunkSize) > bufferSize) {
                chunkSize = (bufferSize - bytesRead);
            }
            // fd, buffer, offset, length, position, callback
            fs.read(fd, buffer, bytesRead, chunkSize, bytesRead,
            function (err, bytes, buff) {
                if (err) return done(err);
                var buffRead = buff.slice(bytesRead, bytesRead+chunkSize);
                // do something with buffRead
                bytesRead += chunkSize;
                done();
            });
        },
        function (err) {
            if (err) console.log(err);
            fs.close(fd);
        }
    );
    
    0 讨论(0)
  • 2020-12-17 15:51

    Since you've designed your app to process files one after another (synchronously), you need to use fs.readSync() but be warned that, while your app is reading a file in this way, it cannot do anything else.

    A better approach would be to process the files in the "node way", that is asynchronously.

    -- node.fs - one line, no waiting

    0 讨论(0)
  • 2020-12-17 15:52

    All of the reads are issued asynchronously using the same buffer (i.e. fs.read returns immediately and the loop continues). By the time the async callback is called the first time, apparently all ten reads have completed (so the buffer contains the results of the last read). Since you called fs.read 10 times, you'll get called back 10 times. So you get what you see.

    The browser shows nothing because you've ended the response before the first callback returns.

    0 讨论(0)
  • 2020-12-17 15:52

    I know this question is not the newest, but I'm going to chuck this up here because when I was getting issues how to open (and read) a filesystem object, a quick search always seemed to direct me here.

    Anyhow, this should help with the OP, and others in the future.

    (filepath is the actual filename, including path)

    fs.open(filepath, '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);
                bytesRead += chunkSize;
            }
            console.log(buffer.toString('utf8', 0, bufferSize));
            fs.close(fd);
        });
    });
    
    0 讨论(0)
提交回复
热议问题