SafeReader.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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(
  45. fd,
  46. buff,
  47. 0,
  48. buff.length,
  49. 0,
  50. function (err, bytesRead, buffer) {
  51. if (err != null) {
  52. return callbackWithClose(err)
  53. }
  54. const result = buffer.toString(encoding, 0, bytesRead)
  55. return callbackWithClose(null, result, bytesRead)
  56. }
  57. )
  58. })
  59. },
  60. }