【问题标题】:how to read ts file and update code dynamically using fs?如何使用 fs 读取 ts 文件并动态更新代码?
【发布时间】:2020-06-23 22:55:01
【问题描述】:

我正在使用 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"
        });
    }
}

【问题讨论】:

    标签: javascript node.js typescript yeoman-generator


    【解决方案1】:

    如果出现错误,您只是记录错误,但继续执行逻辑。因此,您似乎遇到了一个错误,导致res 成为undefined。由于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
        }
    
    }
    

    【讨论】:

    • 感谢它现在正在打印文件的答案,有没有办法像我在我想更改类名的问题中提出的那样更新文件
    • 我已经更新了我的代码,以向您展示如何使用硬编码值以非动态方式执行此操作 - 它应该给您一个开始:)
    • 我尝试使用您的方法,它将导出 CAPICLASS 更新为我想要的类名,但是它没有像我拥有 const request: any = CAPIClass.constructrequest(body); 那样更新其余文件内容我想替换所有字符串如果匹配
    • 啊,你需要一个全局正则表达式,我会编辑我的答案。
    • @hussain:我已经把它改成了正则表达式,现在可以用了吗?
    猜你喜欢
    • 1970-01-01
    • 2019-06-20
    • 1970-01-01
    • 2021-07-11
    • 2012-08-31
    • 2017-11-25
    • 2021-07-27
    • 2014-05-17
    • 1970-01-01
    相关资源
    最近更新 更多