UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

59 lines (56 loc) 2.16 kB
import { mkdir, writeFile as writeFile$1, stat, rename, chown, chmod, unlink } from 'node:fs/promises'; import { dirname } from '@visulima/path'; import { toPath } from '@visulima/path/utils'; import { F_OK } from './F_OK-JER1LjUr.mjs'; import isAccessible from './isAccessible-Bonsm1Ez.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 writeFile = /* @__PURE__ */ __name(async (path, content, options) => { options = { encoding: "utf8", flag: "w", overwrite: true, recursive: true, ...options }; assertValidFileOrDirectoryPath(path); assertValidFileContents(content); path = toPath(path); 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(`${path}.tmp`, toUint8Array(content), { encoding: options.encoding, flag: options.flag }); if (pathExists && !options.overwrite) { stat$1 = await stat(path); if (options.chown === undefined) { options.chown = { gid: stat$1.gid, uid: stat$1.uid }; } await rename(path, `${path}.bak`); } const temporaryPath = `${path}.tmp`; 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(`${path}.tmp`)) { await unlink(`${path}.tmp`); } } }, "writeFile"); export { writeFile as default };