moveAndMaybeCompressFile.js 2.3 KB

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