Javascript 如何使用fs动态读取ts文件和更新代码?
我正在使用yeoman generator搭建新项目,它正在创建所有目录并运行依赖项,现在一旦生成文件,我想更新与appName相同的js类, 首先,我试图读取我未能读取的ts文件,它抛出错误Javascript 如何使用fs动态读取ts文件和更新代码?,javascript,node.js,typescript,yeoman-generator,Javascript,Node.js,Typescript,Yeoman Generator,我正在使用yeoman generator搭建新项目,它正在创建所有目录并运行依赖项,现在一旦生成文件,我想更新与appName相同的js类, 首先,我试图读取我未能读取的ts文件,它抛出错误TypeError:cannotread属性'toString'of undefined,然后我将使用appName更新文件,如果有更好的方法来完成此任务,我将通知帮助 index.js updateTsFile () { const npmdir = `${process.cwd()}/${th
TypeError:cannotread属性'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;
}
预期产量
export class CMyAppNameClass extends Wrapper {
public after = after;
constructor() {
super({
configFileName: "package-name-v1.json"
});
}
}
如果发生错误,您只需记录错误,但继续逻辑。因此,您似乎遇到了一个错误,导致
res
处于未定义状态。由于fs
现在公开了一个基于承诺的api,我将按照如下方式重写它,而不是使用callbacks
(还要注意,您使用utf-8
进行编码,但它应该是utf8
):
谢谢你的回答现在正在打印文件,有没有办法像我在问题中问的那样更新文件我想更改类名我已经更新了我的代码,向您展示了如何使用硬编码值以非动态方式进行更新-这应该给您一个开始:)我尝试使用您的方法,它正在将exportCAPICLASS
更新为我想要的类名,但它没有更新其余的文件内容,比如我的const-request:any=CAPIClass.constructrequest(body)代码>我想替换所有匹配的字符串。如果你需要一个全局正则表达式,我会编辑我的答案。@hussain:我把它改成了正则表达式,现在可以用了吗?
export class CMyAppNameClass extends Wrapper {
public after = after;
constructor() {
super({
configFileName: "package-name-v1.json"
});
}
}
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
}
}