5

I was working on a node module, where I would have to check if the user had installed an specific package (that's the logic I have to follow) and if not, install that using child_process.exec.

That's where the problem appears, even though my script installed the package (node_modules contains it, also package.json), if I call require.resolve again, it says the module does not exist.

For what I found (from node github issues), node has sort of a "cache", where on the first call, if the package is not installed, the cache entry for this package is set to a random value which is not the path to it. Then when you install and try to call that again, it calls that cache entry.

Is there any other way to check if packages are installed, or my local node installation is broken?

falsarella
  • 12,217
  • 9
  • 69
  • 115
PlayMa256
  • 6,603
  • 2
  • 34
  • 54

2 Answers2

3

Take a look into node.js require() cache - possible to invalidate?

It's possible to clean up the require cache, with something like this:

delete require.cache[require.resolve('./module.js')]
falsarella
  • 12,217
  • 9
  • 69
  • 115
2

One way to check if a package is installed is trying to require it. Please see my code below that verifies if a package is not installed. Just add your code that installs it after the comment now install the missing package.

try {
  require('non-existent-package');
} catch (error) {
  // return early if the error is not what we're looking for
  if (error.code != 'MODULE_NOT_FOUND') {
    throw error;
  }
  // now install the missing package
}

Let me know if this works.

bpedro
  • 514
  • 3
  • 5
  • Interesting, if i create a local file with this try catch, it works. Now if i have my module code, linked in a dummy project, running this script, it always throws the error (i.e, installs the package) – PlayMa256 Feb 09 '18 at 11:28
  • The module will only be able to `require` packages inside its own dependency tree, i.e. if you install the missing package on the parent code, the module will not find it. I've reproduced the following behaviors: - Installing the missing package inside the module: it stops throwing the error - Installing the missing package on the `require`r dependency tree: it never stops throwing the error – bpedro Feb 09 '18 at 11:48
  • So, it was not actually a problem on my node... best approach for this would be crawling package.json? – PlayMa256 Feb 09 '18 at 11:50
  • I'm not 100% sure about what you're trying to achieve. Are you trying to install a package on the `require`r code? If so, why do you need to do that? – bpedro Feb 09 '18 at 11:51
  • 1
    Yes, i'm trying. We are trying to make less dependencies as possible, but allow the user to have the option to install something, or not, if needed. But anyways, thanks for the effort. Actually i've discovered something new :) – PlayMa256 Feb 09 '18 at 11:56