@visulima/fs
Version:
Human friendly file system utilities for Node.js
84 lines (77 loc) • 2.88 kB
JavaScript
import { createRequire as __cjs_createRequire } from "node:module";
const __cjs_require = __cjs_createRequire(import.meta.url);
const __cjs_getProcess = typeof globalThis !== "undefined" && typeof globalThis.process !== "undefined" ? globalThis.process : process;
const __cjs_getBuiltinModule = (module) => {
// Check if we're in Node.js and version supports getBuiltinModule
if (typeof __cjs_getProcess !== "undefined" && __cjs_getProcess.versions && __cjs_getProcess.versions.node) {
const [major, minor] = __cjs_getProcess.versions.node.split(".").map(Number);
// Node.js 20.16.0+ and 22.3.0+
if (major > 22 || (major === 22 && minor >= 3) || (major === 20 && minor >= 16)) {
return __cjs_getProcess.getBuiltinModule(module);
}
}
// Fallback to createRequire
return __cjs_require(module);
};
const {
mkdirSync,
writeFileSync: writeFileSync$1,
statSync,
renameSync,
chownSync,
chmodSync,
unlinkSync
} = __cjs_getBuiltinModule("node:fs");
import { dirname } from '@visulima/path';
import { toPath } from '@visulima/path/utils';
import { F_OK } from './F_OK-BalxCn9n.js';
import isAccessibleSync from './isAccessibleSync-38BmiIcx.js';
import assertValidFileContents from './assertValidFileContents-BmcLtsGd.js';
import assertValidFileOrDirectoryPath from './assertValidFileOrDirectoryPath-8HANmVjk.js';
import { t as toUint8Array } from './to-uint-8-array-Dz2nF1y1.js';
const writeFileSync = (path, content, options) => {
options = {
encoding: "utf8",
flag: "w",
overwrite: true,
recursive: true,
...options
};
assertValidFileOrDirectoryPath(path);
assertValidFileContents(content);
path = toPath(path);
const temporaryPath = `${path}.tmp`;
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(temporaryPath, toUint8Array(content), { encoding: options.encoding, flag: options.flag });
if (pathExists && !options.overwrite) {
stat = statSync(path);
if (options.chown === void 0) {
options.chown = { gid: stat.gid, uid: stat.uid };
}
renameSync(path, `${path}.bak`);
}
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(temporaryPath)) {
unlinkSync(`${path}.tmp`);
}
}
};
export { writeFileSync as default };