【问题标题】:node.js/ read 100 first bytes of a filenode.js/ 读取文件的前 100 个字节
【发布时间】:2014-07-06 08:49:31
【问题描述】:

我正在尝试分段读取文件:前 100 个字节,然后…… 我正在尝试读取 /npm 文件的前 100 个字节:

app.post('/random', function(req, res) {
    var start = req.body.start;
    var fileName = './npm';
    var contentLength = req.body.contentlength;
    var file = randomAccessFile(fileName + 'read');
    console.log("Start is: " + start);
    console.log("ContentLength is: " + contentLength);
    fs.open(fileName, 'r', function(status, fd) {
        if (status) {
            console.log(status.message);
            return;
        }
        var buffer = new Buffer(contentLength);
        fs.read(fd, buffer, start, contentLength, 0, function(err, num) {
            console.log(buffer.toString('utf-8', 0, num));
        });
    });

输出是:

Start is: 0
ContentLength is: 100

以及下一个错误:

fs.js:457
  binding.read(fd, buffer, offset, length, position, wrapper);
          ^
Error: Length extends beyond buffer
    at Object.fs.read (fs.js:457:11)
    at C:\NodeInst\node\FileSys.js:132:12
    at Object.oncomplete (fs.js:107:15)

可能是什么原因?

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您混淆了偏移量和位置参数。来自the docs

    offset 是缓冲区中开始写入的偏移量。

    position 是一个整数,指定从文件中的何处开始读取。如果 position 为 null,则从当前文件位置读取数据。

    你应该把你的代码改成这样:

        fs.read(fd, buffer, 0, contentLength, start, function(err, num) {
            console.log(buffer.toString('utf-8', 0, num));
        });
    

    基本上offset 将是 fs.read 将写入缓冲区的索引。假设您有一个长度为 10 的缓冲区,如下所示:<Buffer 01 02 03 04 05 06 07 08 09 0a>,您将从基本上只有零的 /dev/zero 读取,并将偏移量设置为 3 并将长度设置为 4,然后您将得到:@987654329 @。

    fs.open('/dev/zero', 'r', function(status, fd) {
        if (status) {
            console.log(status.message);
            return;
        }
        var buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
        fs.read(fd, buffer, 3, 4, 0, function(err, num) {
            console.log(buffer);
        });
    });
    

    还可以使用fs.createStream 制作您可能想尝试的东西:

    app.post('/random', function(req, res) {
        var start = req.body.start;
        var fileName = './npm';
        var contentLength = req.body.contentlength;
        fs.createReadStream(fileName, { start : start, end: contentLength - 1 })
            .pipe(res);
    });
    

    【讨论】:

    • 别忘了关闭文件描述符:fs.close(fd);
    【解决方案2】:

    从节点 10 开始,有实验性的 Readable[Symbol.asyncIterator](在节点 v12 中不再是实验性的)。

    'use strict';
    
    const fs = require('fs');
    
    async function run() {
      const file = 'hello.csv';
      const stream = fs.createReadStream(file, { encoding: 'utf8', start: 0, end: 100 });
      for await (const chunk of stream) {
        console.log(`${file} >>> ${chunk}`);
      }
    
      // or if you don't want the for-await-loop
      const stream = fs.createReadStream(file, { encoding: 'utf8', start: 0, end: 100 });
      const firstByte = await stream[Symbol.asyncIterator]().next();
      console.log(`${file} >>> ${firstByte.value}`);
    }
    
    run();
    

    将打印出第一口

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多