我有此代码:
哪个会收到2个参数,第一个是script
,它只是一个Linux命令,另一个是template
,它只是一个字符串,给出html模板想要使用的用户。
此appCreator
有3种方法,第一种带有注释// remove template from app
的方法将从应用程序文件夹中删除一个html模板。
另一位评论为// copying template
的人只能从TEMPLATE_FOLDER
文件夹中的APP_FOLDER
复制模板。
最后一个带有注释// getting all html files
,仅在app文件夹中找到显式模板上的所有html,然后替换html中的文本PASTEROCK_SCRIPT
,并放入脚本文本。 / p>
此代码有效...不错,但不合适,因为同步javascript不尊重该功能。
使用数字,您可以检查运行方式...而且我想遵守订单...类似这样的东西:
我该如何解决?
尝试异步并等待:
import * as fs from "fs";
import * as glob from "glob";
import { ncp } from "ncp";
import * as rimraf from "rimraf";
export default async function appCreator(script: string, template: string) {
const APP_FOLDER = `${__dirname}/../app/${template}/`;
const TEMPLATE_FOLDER = `${__dirname}/../template/${template}/`;
// remove template from app
if (fs.existsSync(APP_FOLDER)) {
await rimraf.sync(APP_FOLDER);
}
// copying template
await ncp(TEMPLATE_FOLDER, APP_FOLDER, err => {
if (err) {
console.log(err);
}
});
// getting all html files
await glob.sync(`${APP_FOLDER}**/*.html`).map(file => {
// reading html file
const readFile = fs.readFileSync(file, { encoding: "utf8" });
let replace: string | number = readFile.search("PASTEROCK_SCRIPT");
if (replace !== -1) {
replace = readFile.replace("PASTEROCK_SCRIPT", script);
fs.writeFileSync(file, replace, { encoding: "utf8" });
}
});
}
答案 0 :(得分:0)
我使用的软件包不支持promises ...所以这是解决方案,如果有人想知道的话。包rimraf
是不必要的,因为ncp
替换了所有内容。
import * as fs from "fs";
import { ncp } from "ncp";
import * as glob from "glob";
export default function appCreator(script: string, template: string) {
const APP_FOLDER = `${__dirname}/../app/${template}/`;
const TEMPLATE_FOLDER = `${__dirname}/../template/${template}/`;
// copying or replacing template
ncp(TEMPLATE_FOLDER, APP_FOLDER, err => {
if (err) {
console.log(err);
}
// getting all html files
glob.sync(`${APP_FOLDER}**/*.html`).map(file => {
// reading html file
const readFile = fs.readFileSync(file, { encoding: "utf8" });
let replace: string | number = readFile.search("PASTEROCK_SCRIPT");
if (replace !== -1) {
replace = readFile.replace("PASTEROCK_SCRIPT", script);
fs.writeFileSync(file, replace, { encoding: "utf8" });
}
});
});
}