index.js 914 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. 'use strict';
  2. const fs = require('fs');
  3. const pify = require('pify');
  4. const Buffer = require('safe-buffer').Buffer;
  5. const fsP = pify(fs);
  6. const fsReadP = pify(fs.read, {multiArgs: true});
  7. module.exports = (filepath, pos, len) => {
  8. const buf = Buffer.alloc(len);
  9. return fsP.open(filepath, 'r')
  10. .then(fd =>
  11. fsReadP(fd, buf, 0, len, pos)
  12. .then(readArgs => fsP.close(fd)
  13. .then(() => readArgs))
  14. )
  15. .then(readArgs => {
  16. // TODO: Use destructuring when Node.js 6 is target
  17. const bytesRead = readArgs[0];
  18. let buf = readArgs[1];
  19. if (bytesRead < len) {
  20. buf = buf.slice(0, bytesRead);
  21. }
  22. return buf;
  23. });
  24. };
  25. module.exports.sync = (filepath, pos, len) => {
  26. let buf = Buffer.alloc(len);
  27. const fd = fs.openSync(filepath, 'r');
  28. const bytesRead = fs.readSync(fd, buf, 0, len, pos);
  29. fs.closeSync(fd);
  30. if (bytesRead < len) {
  31. buf = buf.slice(0, bytesRead);
  32. }
  33. return buf;
  34. };