@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 {
mkdir,
writeFile: writeFile$1,
stat,
rename,
chown,
chmod,
unlink
} = __cjs_getBuiltinModule("node:fs/promises");
import { dirname } from '@visulima/path';
import { toPath } from '@visulima/path/utils';
import { F_OK } from './F_OK-BalxCn9n.js';
import isAccessible from './isAccessible-iOp0Bou6.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 writeFile = async (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 = await isAccessible(path, F_OK);
if (!pathExists && options.recursive) {
const directory = dirname(path);
if (!await isAccessible(directory, F_OK)) {
await mkdir(directory, { recursive: true });
}
}
let stat$1;
await writeFile$1(temporaryPath, toUint8Array(content), { encoding: options.encoding, flag: options.flag });
if (pathExists && !options.overwrite) {
stat$1 = await stat(path);
if (options.chown === void 0) {
options.chown = { gid: stat$1.gid, uid: stat$1.uid };
}
await rename(path, `${path}.bak`);
}
if (options.chown) {
try {
await chown(temporaryPath, options.chown.uid, options.chown.gid);
} catch {
}
}
await chmod(temporaryPath, stat$1 && !options.mode ? stat$1.mode : options.mode ?? 438);
await rename(temporaryPath, path);
} catch (error) {
throw new Error(`Failed to write file at: ${path} - ${error.message}`, { cause: error });
} finally {
if (await isAccessible(temporaryPath)) {
await unlink(`${path}.tmp`);
}
}
};
export { writeFile as default };