tempmon
Version:
Monitor for a created folder and automatically generate custom files based on your templates - perfect for development
58 lines (57 loc) • 2.79 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chokidar_1 = __importDefault(require("chokidar"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const dotenv_1 = __importDefault(require("dotenv"));
dotenv_1.default.config();
const watchDirectory = process.env.TEMPMON_WATCH_DIRECTORY || "./src/**";
const tempDirectory = process.env.TEMPMON_TEMPLATE_DIRECTORY || "./template";
const watcher = chokidar_1.default.watch(watchDirectory, {
persistent: true,
ignoreInitial: true,
});
watcher
.on("ready", () => console.log(`[tempmon] ready for changes. template directory -> ${tempDirectory}, watch diretory -> ${watchDirectory}`))
.on("addDir", async (directory) => {
try {
// 1. copy files from template into the created folder
fs_extra_1.default.copySync(tempDirectory, directory);
// 2. convert tempmon__fileName to fileName in the content/file name
const fileArr = directory.split(path_1.default.sep);
const fileName = fileArr[fileArr.length - 1];
const patterns = [
{ from: /\${tempmon__fileName}/gi, to: fileName },
{ from: /\${tempmon__fileName__lowercase}/gi, to: fileName.toLowerCase() },
{ from: /\${tempmon__fileName__UPPERCASE}/gi, to: fileName.toUpperCase() },
{ from: /\${tempmon__fileName__Firstcapital}/gi, to: `${fileName.charAt(0).toUpperCase()}${fileName.substr(1).toLowerCase()}` },
];
const fileNames = await fs_extra_1.default.readdir(directory);
fileNames.forEach((file) => {
// 2.1 convert tempmon__fileName to fileName in the content of the file
const absolutePath = path_1.default.join(directory, file);
let data = fs_extra_1.default.readFileSync(absolutePath, { encoding: "utf8" });
patterns.forEach(({ from, to }) => {
data = data.replace(from, to);
});
fs_extra_1.default.writeFileSync(absolutePath, data);
// 2.2 rename the fileName if it contains tempmon__fileName
patterns.forEach(({ from, to }) => {
const absolutePath = path_1.default.join(directory, file);
if (file.match(from)) {
fs_extra_1.default.renameSync(absolutePath, absolutePath.replace(from, to));
}
});
});
// 3. show completion log
console.log(`[tempmon] custom files have been added in ${directory}`);
}
catch (err) {
console.log(err);
}
});
exports.default = watcher;