[ACCEPTED]-node.js/ read 100 first bytes of a file-node.js

Accepted answer
Score: 24

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

offset is the offset in the buffer 12 to start writing at.

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

You should change 8 your code to this:

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

Basically the offset is will 7 be index that fs.read will write to the 6 buffer. Let's say you have a buffer with 5 length of 10 like this: <Buffer 01 02 03 04 05 06 07 08 09 0a> and you will read 4 from /dev/zero which is basically only zeros, and 3 set the offset to 3 and set the length to 2 4 then you will get this: <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 1 things you might wanna try using 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);
});
Score: 5

Since node 10 there is the experimental 2 Readable[Symbol.asyncIterator] (that is no more experimental in node 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 1 print out the first bites

More Related questions