1 | 'use strict';
|
2 | const fs = require('fs');
|
3 | const pify = require('pify');
|
4 | const withOpenFile = require('with-open-file');
|
5 |
|
6 | const fsReadP = pify(fs.read, {multiArgs: true});
|
7 |
|
8 | const readChunk = (filePath, startPosition, length) => {
|
9 | const buffer = Buffer.alloc(length);
|
10 |
|
11 | return withOpenFile(filePath, 'r', fileDescriptor =>
|
12 | fsReadP(fileDescriptor, buffer, 0, length, startPosition)
|
13 | )
|
14 | .then(([bytesRead, buffer]) => {
|
15 | if (bytesRead < length) {
|
16 | buffer = buffer.slice(0, bytesRead);
|
17 | }
|
18 |
|
19 | return buffer;
|
20 | });
|
21 | };
|
22 |
|
23 | module.exports = readChunk;
|
24 |
|
25 | module.exports.default = readChunk;
|
26 |
|
27 | module.exports.sync = (filePath, startPosition, length) => {
|
28 | let buffer = Buffer.alloc(length);
|
29 |
|
30 | const bytesRead = withOpenFile.sync(filePath, 'r', fileDescriptor =>
|
31 | fs.readSync(fileDescriptor, buffer, 0, length, startPosition)
|
32 | );
|
33 |
|
34 | if (bytesRead < length) {
|
35 | buffer = buffer.slice(0, bytesRead);
|
36 | }
|
37 |
|
38 | return buffer;
|
39 | };
|