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

80.95% Statements 17/21
25% Branches 3/12
88.89% Functions 8/9
82.35% Lines 14/17

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 584x               4x               7x               7x 7x         7x 7x         7x 7x           4x         2x 2x 2x     2x        
import { open, writeFile, close, fdatasync, WriteFileOptions } from "fs";
 
export interface WriteFileAndFlushOptions {
  encoding: BufferEncoding;
  mode: string | number | null | undefined;
  flag: string;
}
 
export const writeFileAndFlush = (
  path: string,
  data: string | NodeJS.ArrayBufferView,
  options: WriteFileAndFlushOptions | BufferEncoding,
  callback: (err?: NodeJS.ErrnoException | null) => void
) => {
  // If options passed in as a string convert to WriteFileAndFlushOptions
  const writeOptions: WriteFileOptions =
    typeof options === "string"
      ? { encoding: options, mode: 0o666, flag: "w" }
      : {
          ...options,
          mode: options.mode ?? 0o666,
        };
 
  // Open the file with same flags and mode as fs.writeFile()
  open(path, writeOptions.flag, writeOptions.mode, (openError, fd) => {
    Iif (openError) {
      return callback(openError);
    }
 
    // It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open!
    return writeFile(fd, data, writeOptions, (writeError) => {
      Iif (writeError) {
        return close(fd, () => callback(writeError)); // still need to close the handle on error!
      }
 
      // Flush contents (not metadata) of the file to disk
      return fdatasync(fd, (syncError) => {
        return close(fd, (closeError) => callback(syncError || closeError)); // make sure to carry over the fdatasync error if any!
      });
    });
  });
};
 
export const writeFileAndFlushAsync = (
  path: string,
  data: string | NodeJS.ArrayBufferView,
  options: WriteFileAndFlushOptions | BufferEncoding = "utf8"
) => {
  return new Promise<void>((resolve, reject) => {
    writeFileAndFlush(path, data, options, (err) => {
      Iif (err) {
        return reject(err);
      }
      return resolve();
    });
  });
};