Manak/npm-programmatic

`list()` fails with ES6 when looking for global packages

Opened this issue · 0 comments

I have a setup where I use ES6 in Node scripts by leveraging the esm package.esm recommends that it should not be installed globally. So when I try to use list() [no parameters] to list globally installed packages, I get the error:

Error: Cannot find module 'esm'
Require stack:
- internal/preload
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at Module._preloadModules (node:internal/modules/cjs/loader:1267:12)
    at loadPreloadModules (node:internal/bootstrap/pre_execution:455:5)
    at prepareMainThreadExecution (node:internal/bootstrap/pre_execution:74:3)
    at node:internal/main/run_main_module:7:1 {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'internal/preload' ]
}

    at ChildProcess.exithandler (node:child_process:333:12)
    at ChildProcess.emit (node:events:376:20)
    at ChildProcess.emit (node:domain:470:12)
    at maybeClose (node:internal/child_process:1063:16)
    at Process.onexit (node:internal/child_process:295:5) {
  killed: false,
  code: 1,
  signal: null,
  cmd: 'npm ls --depth=0 -g ',

It seems to me that this happens because in the code for list() we set cwd to "/" when the search is for global packages. In doing so, the module loader looks for a global install of esm which it fails to find, since esm is only installed locally.

It might help if you allowed list() to accept an opts parameter, like install() and uninstall() so I could pass cwd: '.' to it and your code would have

cwd: opts.cwd?opts.cwd:"/"

instead of

cwd:path?path:"/"

I have tested this by making manual edits to the code in my clone, and it seems to work. I'd be happy to provide a PR.