如何自动将脚本创建的最新目录路径写入配置文件的migrationsDir?
解决方案
步骤1:修复目录创建脚本并添加配置更新逻辑
原脚本存在路径检查错误、路径拼接无效的问题,以下是修改后的完整脚本,新增了自动更新配置文件的功能:
/* eslint-disable no-sync */ import fs from 'fs'; import path from 'path'; // 获取命令行传入的目录名 const folderName = process.argv[2]; if (!folderName) { console.error('请传入要创建的目录名称'); process.exit(1); } // 处理目录路径,转为统一格式的相对路径 const targetDir = path.isAbsolute(folderName) ? path.relative(process.cwd(), folderName) : folderName; const formattedDir = targetDir.startsWith('.') ? targetDir : `./${targetDir}`; try { // 递归创建目录(支持多级目录) if (!fs.existsSync(folderName)) { fs.mkdirSync(folderName, { recursive: true }); console.log('新目录创建成功'); } else { console.log('目录已存在'); } // 更新配置文件中的migrationsDir字段 const configPath = path.join(process.cwd(), 'config.js'); // 配置文件路径,按需修改 let configContent = fs.readFileSync(configPath, 'utf8'); // 正则替换migrationsDir的值,保留配置文件结构 configContent = configContent.replace( /migrationsDir: '.*?'/, `migrationsDir: '${formattedDir}'` ); fs.writeFileSync(configPath, configContent, 'utf8'); console.log('配置文件已更新'); } catch (error) { console.error('操作失败:', error.message); }
步骤2:关键注意事项
- 配置文件路径:脚本默认配置文件为当前工作目录下的
config.js,如果你的配置文件位置或名称不同,请修改configPath变量。 - 路径格式统一:脚本会自动将传入的路径转为相对路径,并统一为
./xxx或../xxx格式,确保与配置文件原有格式一致。 - 正则替换安全:通过精准匹配
migrationsDir: '...'格式进行替换,不会破坏配置文件的其他结构。 - 多级目录支持:添加
{ recursive: true }参数后,可直接创建./a/b/c这类多级嵌套目录。
使用方式
在命令行执行脚本并传入目标目录名:
node your-script-name.js ./new-migration-folder
执行完成后,脚本会自动创建目录(若不存在),并将配置文件中的migrationsDir字段更新为你指定的路径。
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

