Node和Python遍历文件夹自动注入代码

需求是从文件夹中遍历检索多层级文件夹,找到其中文件取到上面namespace 后面的名称,在下面代码中自动注入动态代码:

static displayName = "Test";

在这里插入图片描述

下面使用node和python两种代码实现一下,方便对照学习

node代码


const fs = require('fs');  
const path = require('path');  
  
function traverseFolder(dir, targetString) {  
    fs.readdirSync(dir).forEach((file) => {  
        const filePath = path.join(dir, file);  
        if (fs.statSync(filePath).isDirectory()) {  
            traverseFolder(filePath, targetString);  
        } else {  
            if (fs.readFileSync(filePath, 'utf8').includes(targetString)) {  
                const fileContent = fs.readFileSync(filePath, 'utf8');  
                let result = /namespace\b\s*(\w+)\s*\{/.exec(fileContent);
                let name = result[1];
                let match = /(class Component.*\{)(\s*)/;
                let updatedContent = fileContent.replace(match, `$1 \n        static displayName = "${name}"; $2`);
                fs.writeFileSync(filePath, updatedContent, 'utf8');  
            }  
        }  
    });  
}  

const targetDirectory = './src'; // 替换为你的目录路径  
traverseFolder(targetDirectory, 'namespace ');

python代码

import os  
import re  
  
def traverse_folder(dir_path, target_string):  
    for root, dirs, files in os.walk(dir_path):  

        # for dir in dirs: 
            # print("dir", dir)
        for file in files:  
            file_path = os.path.join(root, file)
            if "tsx" in file and open(file_path, 'r').read().find(target_string) != -1 :  
                    with open(file_path, 'r') as file:  
                        content = file.read()
                    match = re.search(r'namespace\b\s*(\w+)\s*\{', content)  
                    if match:  
                        name = match.group(1)
                        match2 = re.search(r'(class\s+Component.*\{)(\s*)', content)
                        if match2:
                            updated_content = content.replace(match2.group(1), f'{match2.group(1)} \n        static displayName = "{name}";{match2.group(2)}')  
                            with open(file_path, 'w') as file:  
                                file.write(updated_content) 
                 
  
traverse_folder('./src', 'namespace ')  # replace with your directory path
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值