How do I completely destroy an ECMAScript module in nodejs?

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x