How to get package name and version from any `npm install` supported source?

How to get the package name and version from any npm install supported source from within a Node script? I know there is npm view but it appears to only work with npm hosted packages, not for example with packages hosted on Github or local packages.

I’ve written the following module which does a dry-run install of the module and grabs name and version of the package from the command line output. But this works only in one version. It could be extended to other versions if I knew when the command line output changed.

Is there any better way to do this?

Thanks!

const child_process = require("child_process")

module.exports = function (source, silent = false) {
  source = source.replace(/(\s+)/g, '\\$1') //escape spaces
  
  let output 
  try {
    output = child_process.execSync('npm install ' + source + ' --dry-run --loglevel=' + (silent ? 'silent' : 'error')).toString()
  }
  catch (error) {
    // console.log(error.status, error.message)
    // error.stderr
    // error.stdout
  }
  // console.log(output)

  const regex = /^└─┬ (([^ ]*)@([^ \n]*))/gm // tested only with NPM 3.10.10
  
  const match = regex.exec(output)
  
  let result = null
  if (match && match.length > 2) result = {
      name : match[1],
      version : match[2]
  }
  
  return result
}

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.