UNPKG

@thi.ng/file-io

Version:

Assorted file I/O utils (w/ logging support) for NodeJS/Bun

20 lines (19 loc) 812 B
import { isString } from "@thi.ng/checks/is-string"; import { writeFileSync } from "node:fs"; import { writeFile as writeAsync } from "node:fs/promises"; import { ensureDirForFile } from "./dir.js"; import { maskedPath } from "./mask.js"; const writeFile = (path, body, opts, logger, dryRun = false) => __write(writeFileSync, path, body, opts, logger, dryRun); const writeFileAsync = (path, body, opts, logger, dryRun = false) => __write(writeAsync, path, body, opts, logger, dryRun); const __write = (writeFn, path, body, opts, logger, dryRun = false) => { logger?.info( `${dryRun ? "[dryrun] " : ""}writing file: ${maskedPath(path)}` ); if (dryRun) return; ensureDirForFile(path); return writeFn(path, body, !opts && isString(body) ? "utf-8" : opts); }; export { writeFile, writeFileAsync };