美文网首页
基于node遍历文件,批量更改id

基于node遍历文件,批量更改id

作者: 羽晞yose | 来源:发表于2019-10-30 10:50 被阅读0次

在我们使用vue的时候,可能会组件都按照某日期进行管理(至少对到我司,批量活动使用的组件是这样规定的),在下一次用的时候,也需要重新复制这一批次的组件,那么在引入及页面很多地方就有可能出现该id,在复用得时候一个个改容易有纰漏。那么这时候node就可以上场了

// 部分示例,实际id存在多个文件中
import headerTop from '@/mod/public/20191111/secondary/components/headerTop';
import imgLink from '@/mod/public/20191111/secondary/components/imgLink';
import imgLinkSwiper from '@/mod/public/20191111/secondary/components/imgLinkSwiper';
import imgLink3d from '@/mod/public/20191111/secondary/components/imgLink3d';
import interestSwiper from '@/mod/public/20191111/secondary/components/interestSwiper';
import globalTitle from '@/mod/public/20191111/secondary/components/globalTitle';
import categoryCoupon from '@/mod/public/20191111/secondary/components/categoryCoupon';
import seckill from '@/mod/public/20191111/secondary/components/seckill';
import imgLinkSkuCustom from '@/mod/public/20191111/secondary/components/imgLinkSkuCustom';
import productScrollTap from '@/mod/public/20191111/secondary/components/productScrollTap';

我们需要做的,就是将文件夹进行遍历,如果是文件类型,则读取文件,使用正则将文字替换,重新写入文件;如果是文件夹类型则继续遍历进去,代码如下

const fs = require('fs');
const path = require('path'); // 解析需要遍历的文件夹
const filePath = path.resolve('./');

// 读取文件,并且替换文件中指定的字符串
let replaceFile = function (filePath, sourceRegx, targetStr) {
    fs.readFile(filePath, function (err, data) {
        if (err) return err;

        // 使用正则匹配替换掉关键字
        let str = data.toString();
        str = str.replace(sourceRegx, targetStr);

        // 文件重写
        fs.writeFile(filePath, str, function (err) {
            if (err) return err;
        });
    });
}

// 文件遍历方法
function fileDisplay (filePath) {
    // 根据文件路径读取文件,返回文件列表
    fs.readdir(filePath, function (err, files) {
        if (err) {
            console.warn(err)
        } else {
            // 遍历读取到的文件列表
            files.forEach(function (filename) {
                // 获取当前文件的绝对路径
                const filedir = path.join(filePath, filename);

                // 根据文件路径获取文件信息,返回一个fs.Stats对象
                fs.stat(filedir, function (eror, stats) {
                    if (eror) return err;

                    const isFile = stats.isFile(); // 是文件
                    const isDir = stats.isDirectory(); // 是文件夹

                    if (isFile && filename !== 'r.js') replaceFile(filedir, /20191111/g, '20191129');
                    if (isDir) fileDisplay(filedir); // 递归,如果是文件夹,就继续遍历该文件夹下面的文件
                })
            });
        }
    });
}

// 调用文件遍历方法
fileDisplay(filePath);

执行方法:

// 本人电脑是使用git的,所以在需要批量更改ID的文件夹下放入这个文件,执行下面语句
node 文件名.js

关键方法node文档:
path.join([...paths]),这个可能大家比较熟悉,毕竟配置webpack的时候用的较多
fs.readdir(path[, options], callback)
fs.readFile(path[, options], callback)
fs.writeFile(file, data[, options], callback)

相关文章

网友评论

      本文标题:基于node遍历文件,批量更改id

      本文链接:https://www.haomeiwen.com/subject/yzqovctx.html