繁体   English   中英

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

[英]how to read ts file and update code dynamically using fs?

我正在使用 yeoman 生成器搭建新项目,它正在创建所有目录并运行依赖项,现在一旦生成文件,我想更新与 appName 相同的 js class,首先我试图读取我未能执行的 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"
        });
    }
}

预计 output

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
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM