Node使用path和fs进行目录替换

需求:有时候源码文件夹内的某个文件有问题 需要替换才能运行程序,这个时候如何做到每个新人来了拿到项目,在没有任何操作下,运行项目呢?

答:将替换文件的操作放到项目运行或者打包时。

在node模板内根据path和 fs模块来获取文件位置,并替换文件夹目录

首先判断是文件夹,将要替换的文件外部写一个js文件,代码为:

const fs = require('fs');
const path = require('path')
function copyRemFile(originPath, targetPath) {
    try {
        let sourceFile = fs.readdirSync(originPath);
        sourceFile.forEach((file) => {
            const newOriginPath = path.resolve(originPath, file)
            const newTargetPath = path.resolve(targetPath, file)
            let stat = fs.lstatSync(newOriginPath); ##判断是文件夹不
            if (stat.isDirectory()) { #是的话继续循环判断
                copyRemFile(newOriginPath, newTargetPath)
            } else {
                fs.copyFileSync(newOriginPath, newTargetPath) #不是的话 执行替换操作 
            }

        })
    } catch (err) {
        console.log(err);
        return 0;
    }
}
function fixRemFile() {
    const originPath = path.resolve(__dirname, '../**');
    const targetPath = path.resolve(__dirname, '../node_modules/**');

    copyRemFile(originPath, targetPath);
    console.log('兼容文件已替换');
}
module.exports = {
    fixRemFile
}

config文件内执行该函数,那么该函数在项目运行和打包都会执行该方法。

//替换px2rem文件
const {fixRemFile} =require('../fixFile/index')
fixRemFile();

 

posted @ 2022-01-24 16:06  阿兰儿  阅读(297)  评论(0编辑  收藏  举报