source: trip-planner-front/node_modules/streamroller/lib/moveAndMaybeCompressFile.js@ b738035

Last change on this file since b738035 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

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