UNPKG

unbag

Version:

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

102 lines 2.53 kB
import path from "./path.mjs"; import fs from "node:fs/promises"; import fsExtra from "fs-extra/esm"; const useFs = () => { const { readFile, readdir, stat } = fs; const { emptyDir, ensureDir, copy, outputFile, pathExists } = fsExtra; 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.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 { ...fs, outputFile, emptyDir, ensureDir, copy, pathExists, readJson, modifyJson, tryReadJson, listFiles, isFile, isDirectory }; }; export { useFs };