简体   繁体   English

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

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

i am scaffolding new project using yeoman generator it is creating all the directories and running dependencies, now once files are generated i want to update js class same as appName, first i am trying to read the ts file which i failed to do it throws error TypeError: Cannot read property 'toString' of undefined then i would update the file with appName if there is any better approach to achieve this task i will apprecaite the help.我正在使用 yeoman 生成器搭建新项目,它正在创建所有目录并运行依赖项,现在一旦生成文件,我想更新与 appName 相同的 js class,首先我试图读取我未能执行的 ts 文件它会引发错误TypeError: Cannot read property 'toString' of undefined如果有任何更好的方法来完成此任务,我将使用 appName 更新文件,我会感谢帮助。

index.js 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 api.ts

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

expected output预计 output

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

In case of an error you're just logging the error but continuing with the logic.如果出现错误,您只是记录错误但继续执行逻辑。 So it seems like you're running into an error resulting in res being undefined .因此,您似乎遇到了导致resundefined的错误。 Since fs exposes a promise-based api nowadays, I would rewrite this as follows instead of using callbacks (also note that you were using utf-8 for the encoding but it should be utf8 ):由于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