UNPKG

961 BJavaScriptView Raw
1'use strict';
2const fs = require('fs');
3const pify = require('pify');
4const withOpenFile = require('with-open-file');
5
6const fsReadP = pify(fs.read, {multiArgs: true});
7
8const 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
23module.exports = readChunk;
24// TODO: Remove this for the next major release
25module.exports.default = readChunk;
26
27module.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};