Last active
May 14, 2021 00:02
-
-
Save MusiCode1/3c5d1f1f020b882d1a62f64c9a9cec39 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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