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

100% Statements 12/12
100% Branches 1/1
100% Functions 1/1
100% Lines 11/11

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 263x   3x 3x   3x         3x 3x     3x 3x 1x           3x 3x    
import { access, constants, copyFile, rename, writeFile } from "fs-extra";
 
const BACKUP_EXTENSION = "bak";
const TMP_EXTENSION = "new";
 
export const writeFileWithBackupAsync = async (
  path: string,
  data: string | NodeJS.ArrayBufferView,
  options: BufferEncoding | { encoding?: BufferEncoding } = "utf8",
): Promise<void> => {
  const tmpPath = `${path}.${TMP_EXTENSION}`;
  const bakPath = `${path}.${BACKUP_EXTENSION}`;
 
  // Create backup if original exists
  try {
    await access(path, constants.F_OK);
    await copyFile(path, bakPath);
  } catch {
    // File does not exist, no backup needed
  }
 
  // Write .new file and replace existing
  await writeFile(tmpPath, data, options);
  await rename(tmpPath, path);
};