上一主题 下一主题
ScriptCat,新一代的脚本管理器脚本站,与全世界分享你的用户脚本油猴脚本开发指南教程目录
返回列表 发新帖

node查找某个文件,批量修改文件

[复制链接]
  • TA的每日心情
    无聊
    2023-11-2 17:37
  • 签到天数: 275 天

    [LV.8]以坛为家I

    114

    主题

    453

    回帖

    974

    积分

    荣誉开发者

    积分
    974

    荣誉开发者油中2周年卓越贡献生态建设者

    发表于 2024-4-17 17:08:14 | 显示全部楼层 | 阅读模式

    适用于批量修改格式一样的文件

    此篇缘由

    我要批量修改json文件,把某个key对应的value值,之前是对象,我要把对象放到数组里面

    console.log(__dirname);
    const fs = require('fs');
    const path = require('path');
    
    // const directoryPath = __dirname;
    function readJsonFilesInDirectory(directoryPath) {
        fs.readdir(directoryPath, (err, files) => {
          if (err) {
            console.log('Error reading directory:', err);
            return;
          }
          console.log(files)
          files.forEach(file => {
            const filePath = path.join(directoryPath, file);
            fs.stat(filePath, (err, stats) => {
              if (err) {
                console.log('Error stating file:', err);
                return;
              }
              if (stats.isDirectory()) {
                readJsonFilesInDirectory(filePath); // 递归处理子目录
              } else if (path.extname(file) === '.json') {
                console.log(filePath); // 执行你想要的操作
                fs.readFile(filePath, 'utf8', (err, data) => {
                    if (err) {
                      console.error('Error reading file:', err);
                      return;
                    }
    
                    try {
                      let jsonData = JSON.parse(data);
                      if (jsonData.config && typeof jsonData.config === 'object') {
                        jsonData.config = [jsonData.config]; // 将config对象改为包含该对象的数组
                        fs.writeFile(filePath, JSON.stringify(jsonData, null, 2), 'utf8', err => {
                          if (err) {
                            console.error('Error writing file:', err);
                            return;
                          }
                          console.log('File has been successfully modified.');
                        });
                      } else {
                        console.log('The "config" key does not exist or is not an object.');
                      }
                    } catch (error) {
                      console.error('Error parsing JSON:', error);
                    }
                  });
              }
            });
          });
        });
    }
    
    const rootDirectory = __dirname;
    readJsonFilesInDirectory(rootDirectory);
    
    // 这里只能读一个层级目录
    // fs.readdir(directoryPath, (err, files) => {
    //   if (err) {
    //     console.log('Error reading directory:', err);
    //     return;
    //   }
    
    //   const jsonFiles = files.filter(file => path.extname(file) === '.json');
    
    //   jsonFiles.forEach(file => {
    //     console.log(file);
    //     // 这里你可以对每个JSON文件执行你想要的操作
    //   });
    // });
    

    通过遍历我发现某个文件命名不一致,我要查找路径,所以又写了一个node

    const fs = require('fs');
    const path = require('path');
    
    function findFileInDirectory(startPath, targetFile) {
        if (!fs.existsSync(startPath)) {
            console.log("目录不存在:", startPath);
            return;
        }
    
        const files = fs.readdirSync(startPath);
        for (let i = 0; i < files.length; i++) {
            const filename = path.join(startPath, files[i]);
            const stat = fs.lstatSync(filename);
            if (stat.isDirectory()) {
                findFileInDirectory(filename, targetFile); // 递归子目录
            } else if (filename.includes(targetFile)) {
                console.log("找到文件:", filename);
            }
        }
    }
    
    const startPath = './'; // 当前目录
    const targetFile = 'package.bash.json'; // 替换为你要查找的文件名
    findFileInDirectory(startPath, targetFile);

    注意事项

    1.写的过程node的方法要使用对,多个层级目录读取使用的方法不同。

    接脚本定制
    I frequently record, because want to leave something.
  • TA的每日心情
    开心
    2024-3-13 10:14
  • 签到天数: 211 天

    [LV.7]常住居民III

    295

    主题

    3911

    回帖

    3833

    积分

    管理员

    积分
    3833

    管理员荣誉开发者油中2周年生态建设者喜迎中秋油中3周年挑战者 lv2

    发表于 2024-4-17 17:14:57 | 显示全部楼层
    似曾相识

    批量更改文件名,批量解压文件,批量移动
    https://bbs.tampermonkey.net.cn/thread-2888-1-1.html
    (出处: 油猴中文网)
    上不慕古,下不肖俗。为疏为懒,不敢为狂。为拙为愚,不敢为恶。/ 微信公众号:一之哥哥
    回复

    使用道具 举报

  • TA的每日心情
    无聊
    2023-11-2 17:37
  • 签到天数: 275 天

    [LV.8]以坛为家I

    114

    主题

    453

    回帖

    974

    积分

    荣誉开发者

    积分
    974

    荣誉开发者油中2周年卓越贡献生态建设者

    发表于 2024-4-17 18:03:23 | 显示全部楼层
    王一之 发表于 2024-4-17 17:14
    似曾相识

    批量更改文件名,批量解压文件,批量移动

    gg记忆力真好
    接脚本定制
    I frequently record, because want to leave something.
    回复

    使用道具 举报

    发表回复

    本版积分规则

    快速回复 返回顶部 返回列表