All files / src/lib/helpers/fs writeFileWithBackup.ts

86.21% Statements 25/29
40% Branches 2/5
100% Functions 8/8
84.62% Lines 22/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 653x 3x         3x 3x   3x       4x 4x 1x   3x       3x           4x 4x     4x         4x     4x 4x       4x           3x         3x 3x 3x     3x        
import { access, constants, copyFile, renameSync } from "fs";
import {
  WriteFileAndFlushOptions,
  writeFileAndFlush,
} from "./writeFileAndFlush";
 
const BACKUP_EXTENSION = "bak";
const TMP_EXTENSION = "new";
 
export const backupFile = (
  path: string,
  callback: (err?: NodeJS.ErrnoException | null) => void
) => {
  access(path, constants.F_OK, (err) => {
    if (!err) {
      return copyFile(path, `${path}.${BACKUP_EXTENSION}`, callback);
    }
    return callback();
  });
};
 
export const writeFileWithBackup = (
  path: string,
  data: string | NodeJS.ArrayBufferView,
  options: WriteFileAndFlushOptions | BufferEncoding,
  callback: (err?: NodeJS.ErrnoException | unknown | null) => void
) => {
  return backupFile(path, (backupError) => {
    Iif (backupError) {
      return callback(backupError);
    }
    return writeFileAndFlush(
      `${path}.${TMP_EXTENSION}`,
      data,
      options,
      (writeError) => {
        Iif (writeError) {
          return callback(writeError);
        }
        try {
          renameSync(`${path}.new`, path);
        } catch (e) {
          return callback(e);
        }
        return callback();
      }
    );
  });
};
 
export const writeFileWithBackupAsync = (
  path: string,
  data: string | NodeJS.ArrayBufferView,
  options: WriteFileAndFlushOptions | BufferEncoding = "utf8"
) => {
  return new Promise<void>((resolve, reject) => {
    writeFileWithBackup(path, data, options, (err) => {
      Iif (err) {
        return reject(err);
      }
      return resolve();
    });
  });
};