@visulima/fs
Version:
Human friendly file system utilities for Node.js
59 lines (56 loc) • 2.16 kB
JavaScript
import { mkdirSync, writeFileSync as writeFileSync$1, statSync, renameSync, chownSync, chmodSync, unlinkSync } from 'node:fs';
import { dirname } from '@visulima/path';
import { toPath } from '@visulima/path/utils';
import { F_OK } from './F_OK-JER1LjUr.mjs';
import isAccessibleSync from './isAccessibleSync-3gnUWUwX.mjs';
import assertValidFileContents from './assertValidFileContents-Ox-ScfeK.mjs';
import assertValidFileOrDirectoryPath from './assertValidFileOrDirectoryPath-BWWgA1wj.mjs';
import { t as toUint8Array } from './to-uint-8-array-B4CjMOD3.mjs';
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
const writeFileSync = /* @__PURE__ */ __name((path, content, options) => {
options = {
encoding: "utf8",
flag: "w",
overwrite: true,
recursive: true,
...options
};
assertValidFileOrDirectoryPath(path);
assertValidFileContents(content);
path = toPath(path);
try {
const pathExists = isAccessibleSync(path, F_OK);
if (!pathExists && options.recursive) {
const directory = dirname(path);
if (!isAccessibleSync(directory, F_OK)) {
mkdirSync(directory, { recursive: true });
}
}
let stat;
writeFileSync$1(`${path}.tmp`, toUint8Array(content), { encoding: options.encoding, flag: options.flag });
if (pathExists && !options.overwrite) {
stat = statSync(path);
if (options.chown === undefined) {
options.chown = { gid: stat.gid, uid: stat.uid };
}
renameSync(path, `${path}.bak`);
}
const temporaryPath = `${path}.tmp`;
if (options.chown) {
try {
chownSync(temporaryPath, options.chown.uid, options.chown.gid);
} catch {
}
}
chmodSync(temporaryPath, stat && !options.mode ? stat.mode : options.mode ?? 438);
renameSync(temporaryPath, path);
} catch (error) {
throw new Error(`Failed to write file at: ${path} - ${error.message}`, { cause: error });
} finally {
if (isAccessibleSync(`${path}.tmp`)) {
unlinkSync(`${path}.tmp`);
}
}
}, "writeFileSync");
export { writeFileSync as default };