moveAndMaybeCompressFile.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const debug = require('debug')('streamroller:moveAndMaybeCompressFile');
  2. const fs = require('fs-extra');
  3. const zlib = require('zlib');
  4. const moveAndMaybeCompressFile = async (
  5. sourceFilePath,
  6. targetFilePath,
  7. needCompress
  8. ) => {
  9. if (sourceFilePath === targetFilePath) {
  10. debug(
  11. `moveAndMaybeCompressFile: source and target are the same, not doing anything`
  12. );
  13. return;
  14. }
  15. if (await fs.pathExists(sourceFilePath)) {
  16. debug(
  17. `moveAndMaybeCompressFile: moving file from ${sourceFilePath} to ${targetFilePath} ${
  18. needCompress ? "with" : "without"
  19. } compress`
  20. );
  21. if (needCompress) {
  22. await new Promise((resolve, reject) => {
  23. fs.createReadStream(sourceFilePath)
  24. .pipe(zlib.createGzip())
  25. .pipe(fs.createWriteStream(targetFilePath))
  26. .on("finish", () => {
  27. debug(
  28. `moveAndMaybeCompressFile: finished compressing ${targetFilePath}, deleting ${sourceFilePath}`
  29. );
  30. fs.unlink(sourceFilePath)
  31. .then(resolve)
  32. .catch(() => {
  33. debug(`Deleting ${sourceFilePath} failed, truncating instead`);
  34. fs.truncate(sourceFilePath).then(resolve).catch(reject)
  35. });
  36. });
  37. });
  38. } else {
  39. debug(
  40. `moveAndMaybeCompressFile: deleting file=${targetFilePath}, renaming ${sourceFilePath} to ${targetFilePath}`
  41. );
  42. try {
  43. await fs.move(sourceFilePath, targetFilePath, { overwrite: true });
  44. } catch (e) {
  45. debug(
  46. `moveAndMaybeCompressFile: error moving ${sourceFilePath} to ${targetFilePath}`, e
  47. );
  48. debug(`Trying copy+truncate instead`);
  49. await fs.copy(sourceFilePath, targetFilePath, { overwrite: true });
  50. await fs.truncate(sourceFilePath);
  51. }
  52. }
  53. }
  54. };
  55. module.exports = moveAndMaybeCompressFile;