SafeReader.js 1.7 KB

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