You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

合并同名称不同路径JS文件并修改重复变量名的实现咨询

这里有几种实用的方法帮你完成这个需求,从简单手动操作到自动化脚本都有:

方法1:手动处理(适合少量文件场景)

如果只有这两个文件需要处理,手动操作是最直接的:

  • 打开 Result/Apr19/example.js,把内容修改为 var regArr1 = ["A" , "B"];
  • 打开 Result/Apr20/example.js,把内容修改为 var regArr2 = ["C" , "D"];
  • 新建 NewExample.js,将上面两行内容粘贴进去保存即可。
方法2:Node.js自动化脚本(适合批量或重复需求)

如果以后可能有更多类似文件需要合并,写个简单的Node.js脚本可以一键完成工作:

首先创建一个脚本文件(比如命名为mergeScripts.js),写入以下代码:

const fs = require('fs');
const path = require('path');

// 配置需要处理的文件路径和对应的变量名后缀
const inputFiles = [
  { path: 'Result/Apr19/example.js', varSuffix: '1' },
  { path: 'Result/Apr20/example.js', varSuffix: '2' }
];
const outputFile = 'NewExample.js';

// 处理每个文件并合并内容
let combinedContent = '';
inputFiles.forEach((fileInfo, index) => {
  try {
    // 读取目标文件内容
    const content = fs.readFileSync(path.join(__dirname, fileInfo.path), 'utf8');
    // 精准替换变量名(只匹配开头的变量声明)
    const modifiedContent = content.replace(/^var regArr =/, `var regArr${fileInfo.varSuffix} =`);
    // 添加分号和换行,保证格式整洁
    combinedContent += `${modifiedContent.trim()};${index < inputFiles.length - 1 ? '\n' : ''}`;
  } catch (err) {
    console.error(`读取文件 ${fileInfo.path} 出错:`, err);
  }
});

// 将合并后的内容写入新文件
fs.writeFileSync(path.join(__dirname, outputFile), combinedContent, 'utf8');
console.log(`✅ ${outputFile} 已成功生成!`);

使用步骤:

  1. 确保你的电脑已经安装了Node.js(没安装的话直接去官网下载安装即可)
  2. 把这个脚本放在项目根目录(和Result文件夹同级)
  3. 打开终端,进入脚本所在目录,运行命令:node mergeScripts.js
  4. 查看根目录,NewExample.js就已经生成好了!

扩展:适配更多月份的文件

如果以后新增Apr21、Apr22等目录的example.js,只需要修改inputFiles数组,添加对应的路径和后缀即可:

const inputFiles = [
  { path: 'Result/Apr19/example.js', varSuffix: '1' },
  { path: 'Result/Apr20/example.js', varSuffix: '2' },
  { path: 'Result/Apr21/example.js', varSuffix: '3' }
];

甚至可以让脚本自动遍历Result下的所有子目录,无需手动配置路径:

const fs = require('fs');
const path = require('path');

const resultDir = path.join(__dirname, 'Result');
const outputFile = 'NewExample.js';

// 获取Result下的所有子目录
const subDirs = fs.readdirSync(resultDir, { withFileTypes: true })
  .filter(dirent => dirent.isDirectory())
  .map(dirent => dirent.name);

let combinedContent = '';
subDirs.forEach((dirName, index) => {
  const filePath = path.join(resultDir, dirName, 'example.js');
  try {
    const content = fs.readFileSync(filePath, 'utf8');
    const modifiedContent = content.replace(/^var regArr =/, `var regArr${index + 1} =`);
    combinedContent += `${modifiedContent.trim()};${index < subDirs.length - 1 ? '\n' : ''}`;
  } catch (err) {
    console.error(`读取文件 ${filePath} 出错:`, err);
  }
});

fs.writeFileSync(outputFile, combinedContent, 'utf8');
console.log(`✅ ${outputFile} 已成功生成,共合并了 ${subDirs.length} 个文件!`);

这样不管新增多少个月份的目录,脚本都能自动处理,非常省心。

内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:05:47