const path = require('path'); const glob = require('glob'); const fs = require('fs'); /** * 检测目标地址是不是目录 * @param {String} path */ const isDir = path => { let stat = fs.statSync(path); return stat.isDirectory(); }; /** * 建立目标目录 * @description 这里用同步的方法检测目录是否存在,若是失败则认为是不存在,则建立目录; * @param {String} path 目标目录地址 */ const mkdir = path => { try { fs.statSync(path); } catch (e) { fs.mkdirSync(path); } }; /** * 复制文件 * @param {String} source 源文件地址 * @param {String} target 目标文件地址 */ const copyFile = (source, target) => { let data = fs.readFileSync(source, 'utf8'); fs.writeFileSync(target, data, 'utf8'); }; /** * 读取资源目录下的全部文件地址 * @param {String} path */ const readDir = path => { return glob.sync(path); }; /** * 开始 * @param {String} globPath 资源目录 * @param {String} dirPath 目录名称 * @param {String} targetPath 目标目录 */ const start = (globPath, dirPath, targetPath) => { const files = readDir(globPath); for (let i = 0, len = files.length; i < len; i++) { let filePath = files[i]; let targetPath = path.join(__dirname, targetPath, filePath.replace(dirPath, '')); if (isDir(filePath)) { mkdir(targetPath) } else { copyFile(filePath, targetPath); } } }; start('./dist/*/**', './dist/', '../app');
写这个脚本的场景:使用 vue-cli 开发多页面应用,可是须要将构建后的文件成天复制到另外一个工程目录下。javascript