javascript node.js/ 读取文件的前 100 个字节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23720032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:26:40  来源:igfitidea点击:

node.js/ read 100 first bytes of a file

javascriptnode.js

提问by Or Smith

I'm trying to read a file in parts: the first 100 bytes and then on.. I'm trying to read the first 100 bytes of the /npmfile:

我正在尝试分部分读取文件:前 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));
        });
    });

the output is:

输出是:

Start is: 0
ContentLength is: 100

and the next error:

和下一个错误:

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)

What can be the reason?

原因是什么?

回答by Farid Nouri Neshat

You're confusing the offset and position argument. From the docs:

你混淆了偏移量和位置参数。从文档

offsetis the offset in the buffer to start writing at.

positionis an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

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

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

You should change your code to this:

您应该将代码更改为:

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

Basically the offsetis will be index that fs.read will write to the buffer. Let's say you have a buffer with length of 10 like this: <Buffer 01 02 03 04 05 06 07 08 09 0a>and you will read from /dev/zerowhich is basically only zeros, and set the offset to 3 and set the length to 4 then you will get this: <Buffer 01 02 03 00 00 00 00 08 09 0a>.

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

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

Also to make things you might wanna try using fs.createStream:

还要制作您可能想尝试使用的东西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);
});

回答by Manuel Spigolon

Since node 10 there is the experimental Readable[Symbol.asyncIterator](that is no more experimental in node v12).

由于节点 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();

Will print out the first bites

将打印出第一口