My electron project requires users to modify the HOOK script, which can be applied to nodejs immediately.
The relevant code for this function is as follows:
const {ipcMain} = require("electron")
const ipc = require("./IPCCommands")
// start hook
ipcMain.handle(ipc.hook.RUN, AnyproxyRule.compileHook)
// delete hook
ipcMain.handle(ipc.hook.DESTROY, AnyproxyRule.destroyHook)
class AnyproxyRule {
static #hookModule
static #script
// Start hook
static async compileHook(event, args) {
// The code file has been generated, just need to concatenate the correct path.
const codeFile = args.id ".mjs"
AnyproxyRule.#hookModule = await import(codeFile)
AnyproxyRule.#script = args
return ipc.response.toSuccess()
}
// delete hook
static destroyHook() {
if (typeof AnyproxyRule.#hookModule.finish === "function") AnyproxyRule.#hookModule.finish()
AnyproxyRule.#hookModule = null
AnyproxyRule.#script = null
}
}
Since the Monaco editor in the project does not support CommonJS, I chose to let users write ECMAScript.
But I ran into a module cache problem.
Suppose the user's HOOK script has only one line of code: console.info("Hello World").
The user tries to run the HOOK script multiple times, but only the first execution can get the output, and the others have no output.
And, the user changed the HOOK code to: console.info("Hello world! Nice to meet you!").
This line of code also cannot execute without terminating the program.
By consulting the nodejs documentation, I learned that nodejs will cache modules according to the file path.
If there is any other way to delete nodejs's cache of the specified module, I don't want to use temporary files to avoid the cache, it will definitely waste memory.
Is there any way to delete the module cache of nodejs? In particular, remove the module cache for ECAMScript modules.
CodePudding user response:
No, there is no way to do this with ESM in Node.js or browsers at the moment.
The cache is designed to be immutable so this is unfortunately expected.
Here is the Node.js issue.
Your only is to write a loader, implement load
and provide custom functionality to do this. There is some further discussion here on how testdouble does this.