UNPKG

vue-ant-patterns

Version:

vue-ant-patterns

89 lines (82 loc) 2.36 kB
/* * @Author: w.pengfei * @Date: 2020-05-26 09:00:18 * @LastEditTime: 2020-07-02 16:28:08 * @Description: '' * @LastEditors: w.pengfei */ const chokidar = require('chokidar'); const { existsSync, readFileSync } = require('fs'); const glob = require('glob'); const slash = require('slash2'); const { join, basename, relative } = require('path'); const signale = require('signale'); const hljs = require('highlight.js'); const cwd = process.cwd(); const absPath = join(cwd, '_site/examples'); module.exports = function middleRawCode(app) { let mockData = getFile(); watch(); function watch() { const watcher = chokidar.watch([absPath], { ignoreInitial: true, }); watcher.on('all', (event, file) => { mockData = getFile(); // signale.success(`Txt ${relative(cwd, file)} get success`); }); } function getFile() { cleanRequireCache(); let ret = {}; if (existsSync(absPath)) { const txtFiles = glob .sync('**/*.vue', { cwd: absPath, }) .map(p => join(absPath, p)); try { ret = txtFiles.reduce((memo, file) => { const reqPth = slash(file.split('_site')[1]); const content = readFileSync(file).toString(); // const tagNameStart = '<pre><code class="language-html">'; // const tagNameEnd = '</code><pre>'; // const parseContent = hljs.highlight('html', content, true); // const code = tagNameStart + (parseContent ? parseContent.value : '') + tagNameEnd; const o = {}; // o[reqPth] = { // content, // code, // }; o[reqPth] = content; memo = { ...memo, ...o, }; return memo; }, {}); } catch (e) { signale.error(`Txt ${relative(cwd, file)} get failed`); console.error(e); } } return ret; } function cleanRequireCache() { Object.keys(require.cache).forEach(file => { if (file.indexOf(absPath) > -1) { delete require.cache[file]; } }); } return function(req, res, next) { const exceptPath = req.path; const exceptMethod = req.method.toLowerCase(); const obj = mockData[exceptPath]; if (obj && exceptMethod === 'get') { res.send(obj); } else { next(); } }; };