UNPKG

unbag

Version:

一个专门用来开发npm工具的包

109 lines (108 loc) 2.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useFs = void 0; var _path = _interopRequireDefault(require("./path.cjs")); var _promises = _interopRequireDefault(require("node:fs/promises")); var _esm = _interopRequireDefault(require("fs-extra/esm")); function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } const useFs = () => { const { readFile, readdir, stat } = _promises.default; const { emptyDir, ensureDir, copy, outputFile, pathExists } = _esm.default; const readJson = async path2 => { let jsonObj = void 0; const content = await readFile(path2, "utf-8"); jsonObj = JSON.parse(content || ""); return jsonObj; }; const tryReadJson = async path2 => { let jsonObj = void 0; try { jsonObj = await readJson(path2); } catch (error) { console.log("tryReadJson error:", path2); } return jsonObj; }; const modifyJson = async (path2, modify) => { let oldContent = void 0; let oldJson = void 0; try { oldContent = await readFile(path2, "utf-8"); oldJson = JSON.parse(oldContent || ""); } catch (error) {} const newJson = (await modify(oldJson)) || ""; const detectIndent = await import("detect-indent"); const detectNewline = await import("detect-newline"); const DEFAULT_INDENT = 2; const CRLF = "\r\n"; const LF = "\n"; const indent = detectIndent.default(oldContent || "").indent || DEFAULT_INDENT; const newline = detectNewline.detectNewline(oldContent || ""); let newContent = JSON.stringify(newJson, null, indent); if (newline === CRLF) { newContent = newContent.replace(/\n/g, CRLF) + CRLF; } newContent = newContent + LF; await outputFile(path2, newContent, "utf-8"); }; const listFiles = async dir => { const files = []; dir = dir || "/"; const getFiles = async currentDir => { const fileList = await readdir(currentDir); for (const file of fileList) { const name = _path.default.join(currentDir, file); if ((await stat(name)).isDirectory()) { await getFiles(name); } else { files.push(name); } } }; await getFiles(dir); return files; }; const isFile = async path2 => { try { const _stat = await stat(path2); return _stat.isFile(); } catch { return false; } }; const isDirectory = async path2 => { try { const _stat = await stat(path2); return _stat.isDirectory(); } catch { return false; } }; return { ..._promises.default, outputFile, emptyDir, ensureDir, copy, pathExists, readJson, modifyJson, tryReadJson, listFiles, isFile, isDirectory }; }; exports.useFs = useFs;