我正在使用 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"
});
}
}
最佳答案
如果出现错误,您只需记录错误,但继续执行逻辑。因此,您似乎遇到了错误,导致 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
}
}
关于javascript - 如何使用fs读取ts文件并动态更新代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62536547/