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

Node.js脚本完成用户问答后无法更新文件的问题求助

Node.js脚本修复:无法替换文件占位符的问题

核心问题分析

  1. 提问字段名不匹配:原脚本中提问的name用了Test Plugin、test-plugin这类带空格/特殊字符的命名,且重命名文件时错误引用了不存在的plugin_slug键,导致无法正确获取用户输入值。
  2. 文件操作顺序错误:先重命名文件,再向原路径写入内容,此时原文件已不存在,写入操作无效。
  3. 正则匹配失效:占位符包含空格、连字符等特殊字符时,直接用new RegExp会导致正则语法错误,无法匹配目标内容。

修复后的完整代码

#!/usr/bin/env node

import { program } from 'commander';
import { execa } from 'execa';
import inquirer from 'inquirer';
import fs from 'fs';
import path from 'path';

program
  .command('make-plugin <folder-name>')
  .description('克隆仓库并替换占位符')
  .action(async (folderName) => {
    const repoURL = 'https://github.com/wpdev95/plugin-boiler';
    const targetFolder = path.resolve(process.cwd(), folderName);

    // 克隆仓库
    await execa('git', ['clone', repoURL, folderName]);

    const questions = [
      {
        type: 'input',
        name: 'pluginName',
        message: '你的插件名称是什么?',
      },
      {
        type: 'input',
        name: 'pluginSlug',
        message: '你的插件slug是什么?',
      },
      {
        type: 'input',
        name: 'pluginAuthor',
        message: '插件作者名称是什么?',
      },
    ];

    // 获取用户回答
    const answers = await inquirer.prompt(questions);

    // 转义正则特殊字符的工具函数
    const escapeRegExp = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

    // 遍历目标文件夹下的所有文件
    const files = fs.readdirSync(targetFolder).filter(file => {
      const filePath = path.join(targetFolder, file);
      return fs.statSync(filePath).isFile();
    });
    
    for (const file of files) {
      const filePath = path.join(targetFolder, file);
      let content = fs.readFileSync(filePath, 'utf-8');
    
      // 替换文件中的占位符
      for (const key in answers) {
        // 对应原仓库中的占位符格式,比如{{pluginName}}、{{pluginSlug}}等
        const placeholder = `{{${key}}}`;
        const escapedPlaceholder = escapeRegExp(placeholder);
        const replacement = answers[key];
        content = content.replace(new RegExp(escapedPlaceholder, 'g'), replacement);
      }

      // 先写入替换后的内容到原文件
      fs.writeFileSync(filePath, content, 'utf-8');
    
      // 再重命名PHP主文件
      if (file === 'plugin-boilerplate.php') {
        const newPhpFileName = `${answers.pluginSlug}.php`;
        const newPhpFilePath = path.join(targetFolder, newPhpFileName);
        fs.renameSync(filePath, newPhpFilePath);
      }
    }

    console.log('插件模板生成成功!愉快编码!:D');
  });

program.parse(process.argv);

关键修改说明

  • 规范提问字段名:将提问的name改为pluginName、pluginSlug、pluginAuthor这类无特殊字符的变量名,确保后续能正确调用用户输入值。
  • 调整文件操作顺序:先完成内容替换并写入原文件,再执行重命名操作,避免写入路径不存在的问题。
  • 正则转义处理:新增escapeRegExp工具函数,转义占位符中的特殊字符,保证正则匹配的准确性。
  • 统一变量调用方式:重命名文件时直接使用answers.pluginSlug,与提问字段名保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:17:52