將指定目錄下的全部資源總體遷移到另外一個目錄下

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

  • dist 是 vue-cli 建立的工程資源發佈的目錄
  • app 目錄與 vue-cli 工程同級的目標工程
相關文章
相關標籤/搜索