SafeReader.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /* eslint-disable
  2. handle-callback-err,
  3. no-unused-vars,
  4. node/no-deprecated-api,
  5. */
  6. // TODO: This file was created by bulk-decaffeinate.
  7. // Fix any style issues and re-enable lint.
  8. /*
  9. * decaffeinate suggestions:
  10. * DS101: Remove unnecessary use of Array.from
  11. * DS102: Remove unnecessary code created because of implicit returns
  12. * DS207: Consider shorter variations of null checks
  13. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  14. */
  15. let SafeReader
  16. const fs = require('fs')
  17. const logger = require('logger-sharelatex')
  18. module.exports = SafeReader = {
  19. // safely read up to size bytes from a file and return result as a
  20. // string
  21. readFile(file, size, encoding, callback) {
  22. if (callback == null) {
  23. callback = function (error, result) {}
  24. }
  25. return fs.open(file, 'r', function (err, fd) {
  26. if (err != null && err.code === 'ENOENT') {
  27. return callback()
  28. }
  29. if (err != null) {
  30. return callback(err)
  31. }
  32. // safely return always closing the file
  33. const callbackWithClose = (err, ...result) =>
  34. fs.close(fd, function (err1) {
  35. if (err != null) {
  36. return callback(err)
  37. }
  38. if (err1 != null) {
  39. return callback(err1)
  40. }
  41. return callback(null, ...Array.from(result))
  42. })
  43. const buff = Buffer.alloc(size) // fills with zeroes by default
  44. return fs.read(fd, buff, 0, buff.length, 0, function (
  45. err,
  46. bytesRead,
  47. buffer
  48. ) {
  49. if (err != null) {
  50. return callbackWithClose(err)
  51. }
  52. const result = buffer.toString(encoding, 0, bytesRead)
  53. return callbackWithClose(null, result, bytesRead)
  54. })
  55. })
  56. }
  57. }