All files / src/utils fs.js

84.21% Statements 16/19
80% Branches 8/10
100% Functions 2/2
83.33% Lines 15/18

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          1x 1x           1x         1x               2x 1x     1x   1x 7x     7x 1x                         2x 2x 2x     2x        
import fs from 'fs';
import os from 'os';
 
import { promisify } from './utils.js';
 
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
 
/**
 * Carriage return character code.
 * @type {number}
 */
const cr = '\r'.charCodeAt(0);
/**
 * Line feed character code.
 * @type {number}
 */
const lf = '\n'.charCodeAt(0);
 
/**
 * Retrieves the end-of-line (EOL) sequence from a file.
 * @param {string} path - The path to the file.
 * @returns {Promise<string | undefined>} A promise that resolves with the EOL sequence found in the file, or undefined.
 */
async function getEolFromFile(path) {
  if (!fs.existsSync(path)) {
    return undefined;
  }
 
  const buffer = await readFile(path);
 
  for (let i = 0; i < buffer.length; ++i) {
    Iif (buffer[i] === cr) {
      return '\r\n';
    }
    if (buffer[i] === lf) {
      return '\n';
    }
  }
  return undefined;
}
 
/**
 * Writes data to a file while preserving the original end-of-line (EOL) sequence.
 * @param {string} path - The path to the file.
 * @param {string} data - The data to write.
 * @returns {Promise<void>} A promise that resolves when the file is successfully written.
 */
async function writeFilePreservingEol(path, data) {
  const eol = (await getEolFromFile(path)) || os.EOL;
  let result = data;
  Iif (eol !== '\n') {
    result = result.replace(/\n/g, eol);
  }
  await writeFile(path, result);
}
 
export { writeFilePreservingEol };