将指定目录下的所有资源整体迁移到另一个目录下

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 开发多页面应用,但是需要将构建后的文件整天复制到另一个工程目录下。

  • dist 是 vue-cli 创建的工程资源发布的目录
  • app 目录与 vue-cli 工程同级的目标工程
posted @ 2018-02-27 11:41  月半流云  阅读(331)  评论(0编辑  收藏  举报