2017-08-18 06:17:01 -04:00
|
|
|
fs = require "fs"
|
2017-09-07 06:55:50 -04:00
|
|
|
logger = require "logger-sharelatex"
|
2017-08-18 06:17:01 -04:00
|
|
|
|
|
|
|
module.exports = SafeReader =
|
|
|
|
|
|
|
|
# safely read up to size bytes from a file and return result as a
|
|
|
|
# string
|
|
|
|
|
|
|
|
readFile: (file, size, encoding, callback = (error, result) ->) ->
|
|
|
|
fs.open file, 'r', (err, fd) ->
|
2017-09-07 06:56:03 -04:00
|
|
|
return callback() if err? and err.code is 'ENOENT'
|
2017-08-18 06:17:01 -04:00
|
|
|
return callback(err) if err?
|
|
|
|
|
|
|
|
# safely return always closing the file
|
2017-10-02 10:44:00 -04:00
|
|
|
callbackWithClose = (err, result...) ->
|
2017-08-18 06:17:01 -04:00
|
|
|
fs.close fd, (err1) ->
|
|
|
|
return callback(err) if err?
|
|
|
|
return callback(err1) if err1?
|
2017-10-02 10:44:00 -04:00
|
|
|
callback(null, result...)
|
2017-08-18 06:17:01 -04:00
|
|
|
|
|
|
|
buff = new Buffer(size, 0) # fill with zeros
|
|
|
|
fs.read fd, buff, 0, buff.length, 0, (err, bytesRead, buffer) ->
|
|
|
|
return callbackWithClose(err) if err?
|
|
|
|
result = buffer.toString(encoding, 0, bytesRead)
|
2017-10-02 10:44:00 -04:00
|
|
|
callbackWithClose(null, result, bytesRead)
|