UNPKG

@tomjs/node-utils

Version:

A collection of functions for `node.js` projects

99 lines (98 loc) • 2.16 kB
import fs from "node:fs"; import fsp from "node:fs/promises"; import path from "node:path"; function readFileSync(path2) { return fs.readFileSync(path2, "utf8"); } function readFile(path2) { return fsp.readFile(path2, "utf8"); } function writeFileSync(path2, data) { fs.writeFileSync(path2, data, "utf8"); } function writeFile(path2, data) { return fsp.writeFile(path2, data, "utf8"); } function readJsonSync(path2) { if (fs.existsSync(path2)) { return JSON.parse(readFileSync(path2)); } } async function readJson(path2) { if (fs.existsSync(path2)) { const text = await readFile(path2); return JSON.parse(text); } } function writeJsonSync(path2, data, options) { const opts = Object.assign( { replacer: null, space: 2 }, options ); writeFileSync( path2, typeof data === "string" ? data : JSON.stringify(data, opts.replacer, opts.space) ); } function writeJson(path2, data, options) { const opts = Object.assign( { replacer: null, space: 2 }, options ); return writeFile( path2, typeof data === "string" ? data : JSON.stringify(data, opts.replacer, opts.space) ); } const checkPath = (pth) => { if (process.platform === "win32") { const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, "")); if (pathHasInvalidWinCharacters) { const error = new Error(`Path contains invalid characters: ${pth}`); error.code = "EINVAL"; throw error; } } }; function mkdir(dir, mode) { checkPath(dir); return fsp.mkdir(dir, { mode: mode ?? 511, recursive: true }); } function mkdirSync(dir, mode) { checkPath(dir); return fs.mkdirSync(dir, { mode: mode ?? 511, recursive: true }); } function removeFile(path2) { return fsp.rm(path2, { force: true, recursive: true }); } function removeFileSync(path2) { fs.rmSync(path2, { force: true, recursive: true }); } const index = {}; export { index as default, mkdir, mkdirSync, readFile, readFileSync, readJson, readJsonSync, removeFile, removeFileSync, writeFile, writeFileSync, writeJson, writeJsonSync };