Skip to content

Instantly share code, notes, and snippets.

@MusiCode1
Last active May 14, 2021 00:02
Show Gist options
  • Save MusiCode1/3c5d1f1f020b882d1a62f64c9a9cec39 to your computer and use it in GitHub Desktop.
Save MusiCode1/3c5d1f1f020b882d1a62f64c9a9cec39 to your computer and use it in GitHub Desktop.

בדיקת טעינה מחדש של מודולים

const { writeFile, readFile } = require("fs").promises;
module.exports = {
Class,
sleep,
change_file
};
function Class() {
let interval;
this.start = () => {
let i = 1;
const text = "first text"; // "last text"
interval = setInterval(() => {
console.log(i + " " + text);
i++;
}, 500);
};
this.stop = () => {
clearInterval(interval);
};
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function change_file(path, fn) {
const script_text = await readFile(path, "utf-8");
const new_script_text = fn(script_text);
await writeFile(path, new_script_text, "utf-8");
}
const { join } = require("path");
const script = join(__dirname, "class-to-reload.js");
(async function main() {
let { Class, sleep, change_file } = require(script);
console.log("start...");
let the_class = new Class();
the_class.start();
await sleep(1000 * 2);
console.log("change script file...");
await change_file(script, (script_text) =>
script_text.replace("\"first text\"", "\"last text\"")
);
// https://stackoverflow.com/a/11477602/12054906
delete require.cache[require.resolve(script)];
Class = require(script).Class;
await sleep(1000 * 2);
console.log("stop!");
the_class.stop();
the_class = new Class();
the_class.start();
await sleep(1000 * 5);
console.log("stop!");
the_class.stop();
console.log("re change script file...");
await change_file(script, (script_text) =>
script_text.replace("\"last text\"", "\"first text\"")
);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment