获取节点中模块的路径(模块文件夹,而不是入口文件)

时间:2019-06-30 06:08:55

标签: javascript node.js

我希望能够在构建时在节点中查找模块的路径。

我在文档中看到有这样的require.resolve

// get path to module 'foo'
console.log(require.resolve('foo'));

但这会寻找到模块入口的路径。如果模块没有入口点(它只是共享文件的集合),则require.resolve会失败。

我知道在某些情况下我只能看node_modules/name-of-module,但是在各种情况下那是错误的。例如,我将'foo'作为依赖项,并将'foo'作为'bar'作为依赖项。然后默认情况下,bar将位于project-root/node_modules/bar中,但是如果我npm link'foo',则'bar'将位于project-root/node_modules/foo(link)/node_modules/bar

我考虑过放置一个虚拟条目,该条目适用于我自己的模块,但不适用于我无法控制的模块。

是否有某种方法可以找到给定模块的根文件夹的路径?

还有一种方法可以从其他模块的上下文中获取模块的路径。

换句话说,如果我愿意的话

const bar = require('bar');

这就是要在我的package.json中引用的“ bar”模块。想象还有其他包含“ bar”版本的软件包“ foo”。我想问一个问题:“ foo”包对于“ bar”的路径是什么?”

我要解决的实际问题是在构建时将某些文件从某个模块复制到构建的输出文件夹中,但要做到这一点,我需要能够找到该模块。 / p>

我可以一起破解某些东西,但是假设它们是正确的方法,那么最好以“正确”的方式进行操作。

2 个答案:

答案 0 :(得分:0)

我想我可以直接依赖

const path = require('path');
const fs = require('fs');

function exists(filename) {
  try {
    const stat = fs.statSync(filename);
    return true;
  } catch (e) {
    return false;
  }
}

function getModulePath(name) {
  for (const dirname of require.resolve.paths(name)) {
    const filename = path.join(dirname, name);
    if (exists(filename)) {
      return filename;
    }
  }
}

对于间接依赖性,我必须使直接依赖性进行查找。至少对于问题中提到的npm link情况。

答案 1 :(得分:0)

我认为可以达到目的:

function pathForModuleAsAnotherModule(get, another) {
    let m = require('module')
    let anotherLocation = require.resolve(another);
    let anotherDir = require('path').dirname(anotherLocation);
    let anotherPaths = m.Module._nodeModulePaths(anotherDir)
    return require.resolve(get, { paths: anotherPaths })
}

然后:

pathForModuleAsAnotherModule('foo', 'bar')
相关问题