javascript - 如何使用fs读取ts文件并动态更新代码?

标签 javascript node.js typescript yeoman-generator

我正在使用 yeoman 生成器搭建新项目,它正在创建所有目录并运行依赖项,现在生成文件后我想更新与 appName 相同的 js 类, 首先,我尝试读取 ts 文件,但我没能做到,它会抛出错误 TypeError: Cannot read property 'toString' of undefined 然后,如果有任何更好的方法来实现,我将使用 appName 更新文件这项任务我将感谢您的帮助。

index.js

 updateTsFile () {
    const npmdir = `${process.cwd()}/${this.props.appName}`;
    const dirPath = `${npmdir}/${"./api.ts"}`;
    console.log("path", dirPath);
    let response;
    _fs.readFile(dirPath, (_err, res) => {
      if (_err) {
        console.error(_err);
      }

      let file = res.toString("utf-8");
      console.log(file);
      response = file;
      let lines = file.split("\n");
      for (let i = 0; i < lines.length; i++) {
        console.log(lines[i]);
      }
    });
    return response;
  }

api.ts

export class CAPIClass extends Wrapper {
    public after = after;
    constructor() {
        super({
            configFileName: "package-name-v1.json"
        });
    }
}

预期输出

export class CMyAppNameClass extends Wrapper {
    public after = after;
    constructor() {
        super({
            configFileName: "package-name-v1.json"
        });
    }
}

最佳答案

如果出现错误,您只需记录错误,但继续执行逻辑。因此,您似乎遇到了错误,导致 resundefined。由于 fs 现在公开了基于 Promise 的 api,我将按如下方式重写它,而不是使用 callbacks (另请注意,您使用的是 utf-8 > 编码但应该是 utf8):

async updateTsFile() {
    const npmdir = `${process.cwd()}/${this.props.appName}`;
    const dirPath = `${npmdir}/${"./api.ts"}`;
    console.log("path", dirPath);

    try {
        const fileData = await _fs.promises.readFile(dirPath);
        const fileAsStr = fileData.toString("utf8");

        // replace class-name
        fileAsStr = fileAsStr.replace(/CAPIClass/g, "CMyAppNameClass");
        // (over)write file: setting 'utf8' is not actually needed as it's the default
        await _fs.promises.writeFile(dirPath, fileAsStr, 'utf8');
    } catch (err) {
        console.log(err);
        // handle error here
    }

}

关于javascript - 如何使用fs读取ts文件并动态更新代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62536547/

相关文章:

node.js - Azure DevOps 管道打开的文件太多

javascript - 使用 Jest 测试 ES6 类时出现问题

node.js - 合并不使用 Object.assign() 的 Apollo Server 的 GraphQL 解析器

javascript - 为什么这个冒泡排序不起作用

typescript - 编译后的 Type Script 指的是全局范围的 this

javascript - 将节点与中断标签一起附加到文档片段

javascript - 如何解决 "Cannot read property ' scrollIntoView' of undefined"?

javascript - 如何为 ngrx/store 2.2.1 配置 system-config.js

node.js - 错误 TS2307 : Cannot find module 'app'

javascript - 使用 Javascript 动态着色美国 map