node.js fs.read() 示例

发布于 2024-11-07 02:36:54 字数 2134 浏览 0 评论 0原文

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',function(err,fd){
  fs.fstat(fd,function(err, stats){
   var i=0
   var s=stats.size
   console.log('.'+req.url+' '+s)
   for(i=0;i<s;console.log(i)){
    i=i+buffer.length
    fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){
     res.write(b.toString('utf8',0,l))
     console.log(b.toString('utf8',0,l))
    })
   }
   res.end()
   fs.close(fd)
  })
 })
}
http = require('http')
server = http.createServer(app)
server.listen(8000,"127.0.0.1")
console.log('GET http://127.0.0.1:8000/appwsgi/www/index.htm')

为什么这仅多次显示 979 字节文件中的最后 100 字节?

为什么chrome浏览器不显示任何输出?

gert@node:~/http$ node server.js 
GET http://127.0.0.1:8000/appwsgi/www/index.htm
./appwsgi/www/index.htm 979
100
200
300
400
500
600
700
800
900
1000
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>
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',function(err,fd){
  fs.fstat(fd,function(err, stats){
   var i=0
   var s=stats.size
   console.log('.'+req.url+' '+s)
   for(i=0;i<s;console.log(i)){
    i=i+buffer.length
    fs.read(fd,buffer,0,buffer.length,i,function(e,l,b){
     res.write(b.toString('utf8',0,l))
     console.log(b.toString('utf8',0,l))
    })
   }
   res.end()
   fs.close(fd)
  })
 })
}
http = require('http')
server = http.createServer(app)
server.listen(8000,"127.0.0.1")
console.log('GET http://127.0.0.1:8000/appwsgi/www/index.htm')

Why does this only show the last 100 bytes multiple times from a 979 bytes file?

Why does chrome browser not show any output?

gert@node:~/http$ node server.js 
GET http://127.0.0.1:8000/appwsgi/www/index.htm
./appwsgi/www/index.htm 979
100
200
300
400
500
600
700
800
900
1000
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

oad.<br/>
   <a href=
"vi/vi.htm">vi</a> Edit online files on the server.
  </div>
 </body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

握住你手 2024-11-14 02:36:54

我知道这个问题不是最新的,但我将把这个问题放在这里,因为当我遇到如何打开(和读取)文件系统对象的问题时,快速搜索似乎总是将我引导到这里。

无论如何,这应该对 OP 以及未来的其他人有所帮助。

(filepath是实际的文件名,包括路径)

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);
    });
});

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);
    });
});
杀お生予夺 2024-11-14 02:36:54

所有读取都是使用相同的缓冲区异步发出的(即 fs.read 立即返回并且循环继续)。当第一次调用异步回调时,显然所有十个读取都已完成(因此缓冲区包含上次读取的结果)。由于您调用了 fs.read 10 次,因此您将收到 10 次回调。所以你得到你所看到的。

浏览器不会显示任何内容,因为您在第一个回调返回之前就结束了响应。

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.

赤濁 2024-11-14 02:36:54

我使用上面的 @user1256169 示例来创建我需要的内容。这里我使用 async.whilst 来更干净地处理异步控制流。在示例的顶部,我正在同步读取文件及其统计信息,但如果需要,可以更改。

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);
    }
);

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);
    }
);
镜花水月 2024-11-14 02:36:54

由于您已将应用程序设计为逐个(同步)处理文件,因此您需要使用 fs.readSync() 但请注意,当您的应用程序以这种方式读取文件时,它无法执行任何其他操作。

更好的方法是以“节点方式”处理文件,即异步。

-- node.fs - 一行,无需等待

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文