Reputation: 4427
I have this code:
Which receive 2 args, the first is script
, it's only a linux command, and the other is template
, it's only a string that gives what html template wants to use an user.
this appCreator
has 3 methods, the first with the comment // remove template from app
will remove one html template from the app folder.
Another with the comment // copying template
only copy a template from TEMPLATE_FOLDER
on APP_FOLDER
folder.
And the last one is with the comment // getting all html files
, only find all the html on a explicite template from the app folder, and replace the text PASTEROCK_SCRIPT
from the html, putting the script text.
This code works... Nice, but not appropriately, because the synchronous javascript does not respect the functionality.
With the numbers, you can check the way how is running... And I want to respect the order... Something like this:
How can I resolve it?
With async and await I tried:
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" });
}
});
}
Upvotes: 1
Views: 11148
Reputation: 4427
The packages I use do not support promises... So this is the solution if someone wants to know. The package rimraf
is not necessary because ncp
replace all.
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" });
}
});
});
}
Upvotes: 1