sindresorhus / clear-module

Clear a module from the cache
MIT License
182 stars 25 forks source link

BUG : Clear-module doesn't skip native module #18

Open Fadoli opened 3 years ago

Fadoli commented 3 years ago

Hey we've been using this module a bit, and I've encountered an issue with it.

It seems you don't filter out native module, and as per nodejs documentation this causes bad behavior when re-requiring code later on.

This documentation as been added there : https://github.com/nodejs/node/commit/5c14d695d2c1f924cf06af6ae896027569993a5c

To reproduce, clear-module and reimport any library that internally uses a native library ( '.node' file )

I'm getting an Error: Unknown failure when requiring it back and more specifically when the codes tries to call a function (that's within the .node )

Fadoli commented 3 years ago

from pocking around (in node 14), it seems like we can't properly clean what requires it, a safer approach would be to skip the module whose child is a .node and all its childrens to prevent breaking anything to weirdly.

    // Remove all descendants from cache as well
    if (require.cache[filePath]) {
        const { children } = require.cache[filePath];

        let isSafe = true;
        for (const { id } of children) {
            if (id.endsWith('.node')) {
                isSafe = false;
            }
        }

        if (isSafe) {
            delete require.cache[filePath];

            for (const { id } of children) {
                clear(id);
            }
        }
    }

I don't know if that would impact anyone else's usage.