在不加载的情况下获取已安装的 Node 包的版本号?

Get the version number of an installed Node package without loading it?

有可能to get the version of the current package通过

const { version } = require('./package.json')

但是如何在不加载的情况下获取任意已安装包的版本号?

我找到了 require.resolve 的解决方案:

const path = require('path')

// get version number without requiring the module
function packageVersion(moduleName) {
  const dir = path.dirname(require.resolve(moduleName))
  return require(path.join(dir, 'package.json')).version
}