UNPKG

@oeyoews/tiddlywiki-plugin-dev

Version:

[![](https://img.shields.io/badge/Join-TiddlyWiki_CN-blue)](https://github.com/tiddly-gittly)

99 lines (93 loc) 2.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.walkFilesSync = exports.waitForFile = exports.tryCopy = exports.tiddlywiki = exports.sleep = exports.mkdirsForFileSync = void 0; var _fs = _interopRequireDefault(require("fs")); var _path = require("path"); var _tiddlywiki = require("tiddlywiki"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * 初始化 TiddlyWiki * * @param {Record<string, unknown>[]} [preloadTiddlers=[]] 额外的 tiddler * @param {string} [dir='.'] 工作路径 * @param {string[]} [commands=[]] 附加指令 * @return {ITiddlyWiki} */ const tiddlywiki = (preloadTiddlers = [], dir = '.', commands = []) => { const $tw = (0, _tiddlywiki.TiddlyWiki)(); $tw.boot.argv = [dir, ...commands]; $tw.preloadTiddlerArray(preloadTiddlers); $tw.boot.boot(); return $tw; }; /** * 确保某个文件对应的路径存在 * * @param {string} fileName 文件路径 */ exports.tiddlywiki = tiddlywiki; const mkdirsForFileSync = fileName => { const path = (0, _path.dirname)(fileName); if (!_fs.default.existsSync(path)) { mkdirsForFileSync(path); _fs.default.mkdirSync(path); } }; /** * 尝试深拷贝,from不存在不会出错,to存在也不会出错 * * @param {string} from 源路径 * @param {string} to 目标路径 */ exports.mkdirsForFileSync = mkdirsForFileSync; const tryCopy = (from, to) => { if (_fs.default.existsSync(from)) { _fs.default.cpSync(from, to, { force: true, errorOnExist: false, recursive: true }); } }; /** * 递归遍历所有文件 * * @param {string} dir 根路径 * @param {(filepath: string, stats: fs.Stats) => void} callback 回调函数 */ exports.tryCopy = tryCopy; const walkFilesSync = (dir, callback) => { const stats = _fs.default.statSync(dir); if (stats.isFile()) { callback(dir, stats); } else { _fs.default.readdirSync(dir).forEach(item => walkFilesSync((0, _path.resolve)(dir, item), callback)); } }; /** * 等待若干毫秒 * * @async * @param {number} millionseconds 毫秒数 * @return {Promise<void>} */ exports.walkFilesSync = walkFilesSync; const sleep = millionseconds => new Promise(resolve => setTimeout(() => resolve(), millionseconds)); /** * 等待直到某个文件存在 * * @param {string} path 要检测的文件路径 */ exports.sleep = sleep; const waitForFile = path => new Promise(resolve => { const id = setInterval(() => { resolve(); if (_fs.default.existsSync(path)) { resolve(); clearInterval(id); } }, 100); }); exports.waitForFile = waitForFile;