提问者:小点点

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


我正在使用yeoman generator构建新的项目,它正在创建所有的目录和运行依赖关系,现在一旦文件生成,我想更新js类相同的appName,首先我试图读取ts文件,我失败了,它抛出错误类型错误:不能读取属性‘到字符串’的未定义然后我将更新与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"
        });
    }
}

共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
    }

}