LocalFileWriter.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import fs from 'node:fs'
  2. import crypto from 'node:crypto'
  3. import path from 'node:path'
  4. import Stream from 'node:stream'
  5. import { callbackify, promisify } from 'node:util'
  6. import metrics from '@overleaf/metrics'
  7. import Settings from '@overleaf/settings'
  8. import Errors from './Errors.js'
  9. const { WriteError } = Errors
  10. export default {
  11. promises: {
  12. writeStream,
  13. deleteFile,
  14. },
  15. writeStream: callbackify(writeStream),
  16. deleteFile: callbackify(deleteFile),
  17. }
  18. const pipeline = promisify(Stream.pipeline)
  19. async function writeStream(stream, key) {
  20. const timer = new metrics.Timer('writingFile')
  21. const fsPath = _getPath(key)
  22. const writeStream = fs.createWriteStream(fsPath)
  23. try {
  24. await pipeline(stream, writeStream)
  25. timer.done()
  26. return fsPath
  27. } catch (err) {
  28. await deleteFile(fsPath)
  29. throw new WriteError('problem writing file locally', { fsPath }, err)
  30. }
  31. }
  32. async function deleteFile(fsPath) {
  33. if (!fsPath) {
  34. return
  35. }
  36. try {
  37. await fs.promises.unlink(fsPath)
  38. } catch (err) {
  39. if (err.code !== 'ENOENT') {
  40. throw new WriteError('failed to delete file', { fsPath }, err)
  41. }
  42. }
  43. }
  44. function _getPath(key) {
  45. if (key == null) {
  46. key = crypto.randomUUID()
  47. }
  48. key = key.replace(/\//g, '-')
  49. return path.join(Settings.path.uploadFolder, key)
  50. }