2020-02-19 06:14:28 -05:00
|
|
|
/* eslint-disable
|
|
|
|
no-unused-vars,
|
2022-05-16 10:25:49 -04:00
|
|
|
n/no-deprecated-api,
|
2020-02-19 06:14:28 -05:00
|
|
|
*/
|
|
|
|
// TODO: This file was created by bulk-decaffeinate.
|
|
|
|
// Fix any style issues and re-enable lint.
|
2020-02-19 06:14:14 -05:00
|
|
|
/*
|
|
|
|
* decaffeinate suggestions:
|
|
|
|
* DS101: Remove unnecessary use of Array.from
|
|
|
|
* DS102: Remove unnecessary code created because of implicit returns
|
|
|
|
* DS207: Consider shorter variations of null checks
|
|
|
|
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
|
|
|
|
*/
|
2020-02-19 06:14:37 -05:00
|
|
|
let SafeReader
|
|
|
|
const fs = require('fs')
|
2022-03-01 10:09:36 -05:00
|
|
|
const logger = require('@overleaf/logger')
|
2017-08-18 06:17:01 -04:00
|
|
|
|
2020-02-19 06:14:37 -05:00
|
|
|
module.exports = SafeReader = {
|
|
|
|
// safely read up to size bytes from a file and return result as a
|
|
|
|
// string
|
2017-08-18 06:17:01 -04:00
|
|
|
|
2020-02-19 06:14:37 -05:00
|
|
|
readFile(file, size, encoding, callback) {
|
|
|
|
if (callback == null) {
|
2021-10-27 05:49:18 -04:00
|
|
|
callback = function () {}
|
2020-02-19 06:14:37 -05:00
|
|
|
}
|
2020-08-10 12:01:11 -04:00
|
|
|
return fs.open(file, 'r', function (err, fd) {
|
2020-02-19 06:14:37 -05:00
|
|
|
if (err != null && err.code === 'ENOENT') {
|
|
|
|
return callback()
|
|
|
|
}
|
|
|
|
if (err != null) {
|
|
|
|
return callback(err)
|
|
|
|
}
|
2017-08-18 06:17:01 -04:00
|
|
|
|
2020-02-19 06:14:37 -05:00
|
|
|
// safely return always closing the file
|
|
|
|
const callbackWithClose = (err, ...result) =>
|
2020-08-10 12:01:11 -04:00
|
|
|
fs.close(fd, function (err1) {
|
2020-02-19 06:14:37 -05:00
|
|
|
if (err != null) {
|
|
|
|
return callback(err)
|
|
|
|
}
|
|
|
|
if (err1 != null) {
|
|
|
|
return callback(err1)
|
|
|
|
}
|
|
|
|
return callback(null, ...Array.from(result))
|
|
|
|
})
|
2020-05-07 05:42:05 -04:00
|
|
|
const buff = Buffer.alloc(size) // fills with zeroes by default
|
2021-07-13 07:04:48 -04:00
|
|
|
return fs.read(
|
|
|
|
fd,
|
|
|
|
buff,
|
|
|
|
0,
|
|
|
|
buff.length,
|
|
|
|
0,
|
|
|
|
function (err, bytesRead, buffer) {
|
|
|
|
if (err != null) {
|
|
|
|
return callbackWithClose(err)
|
|
|
|
}
|
|
|
|
const result = buffer.toString(encoding, 0, bytesRead)
|
|
|
|
return callbackWithClose(null, result, bytesRead)
|
2020-02-19 06:14:37 -05:00
|
|
|
}
|
2021-07-13 07:04:48 -04:00
|
|
|
)
|
2020-02-19 06:14:37 -05:00
|
|
|
})
|
2021-07-13 07:04:48 -04:00
|
|
|
},
|
2020-02-19 06:14:37 -05:00
|
|
|
}
|