UNPKG

@visulima/fs

Version:

Human friendly file system utilities for Node.js

61 lines (57 loc) 2.22 kB
'use strict'; const node_fs = require('node:fs'); const path = require('@visulima/path'); const utils = require('@visulima/path/utils'); const F_OK = require('./F_OK-CWSqQIdF.cjs'); const isAccessibleSync = require('./isAccessibleSync-VWjQa-US.cjs'); const assertValidFileContents = require('./assertValidFileContents-CRVvyM6b.cjs'); const assertValidFileOrDirectoryPath = require('./assertValidFileOrDirectoryPath-BMbgA-eI.cjs'); const toUint8Array = require('./to-uint-8-array-BaTEyX3D.cjs'); var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); const writeFileSync = /* @__PURE__ */ __name((path$1, content, options) => { options = { encoding: "utf8", flag: "w", overwrite: true, recursive: true, ...options }; assertValidFileOrDirectoryPath(path$1); assertValidFileContents(content); path$1 = utils.toPath(path$1); try { const pathExists = isAccessibleSync(path$1, F_OK.F_OK); if (!pathExists && options.recursive) { const directory = path.dirname(path$1); if (!isAccessibleSync(directory, F_OK.F_OK)) { node_fs.mkdirSync(directory, { recursive: true }); } } let stat; node_fs.writeFileSync(`${path$1}.tmp`, toUint8Array.toUint8Array(content), { encoding: options.encoding, flag: options.flag }); if (pathExists && !options.overwrite) { stat = node_fs.statSync(path$1); if (options.chown === undefined) { options.chown = { gid: stat.gid, uid: stat.uid }; } node_fs.renameSync(path$1, `${path$1}.bak`); } const temporaryPath = `${path$1}.tmp`; if (options.chown) { try { node_fs.chownSync(temporaryPath, options.chown.uid, options.chown.gid); } catch { } } node_fs.chmodSync(temporaryPath, stat && !options.mode ? stat.mode : options.mode ?? 438); node_fs.renameSync(temporaryPath, path$1); } catch (error) { throw new Error(`Failed to write file at: ${path$1} - ${error.message}`, { cause: error }); } finally { if (isAccessibleSync(`${path$1}.tmp`)) { node_fs.unlinkSync(`${path$1}.tmp`); } } }, "writeFileSync"); module.exports = writeFileSync;