简体   繁体   English

如何在不运行require的情况下知道node.js的完整路径

[英]How can I know the full path node.js will require without running require

I want to be able to know what path node's require will resolve to without running a require. 我希望能够在不运行require的情况下知道节点需要解析的路径。

For example 例如

var myVar = require('./some_module')

Internally node.js will look through its PATH, figure out whether it's a directory, a js file, a json file, etc., and then load the file. 内部node.js将查看其PATH,确定它是一个目录,一个js文件,一个json文件等,然后加载该文件。

Is there a way to just as for the full resolved path without actually loading the module? 有没有办法在没有实际加载模块的情况下完全解析路径?

The output I'm looking for would be something like 我正在寻找的输出将是类似的

/Users/myUser/awesomeProject/some_module.js

The important part being the .js extension, since node would have had to fully resolve the path. 重要的部分是.js扩展,因为节点必须完全解析路径。

note: require('path').resolve ... does not solve this issue. 注意: require('path').resolve ...无法解决此问题。 What if some_module is actually a directory with a package.json inside of it, etc. 如果some_module实际上是一个包含package.json的目录,等等。

Turns out node has a way to do this! 结果节点有办法做到这一点! It's just not easy to find in their documentation. 在他们的文档中找到它并不容易。 Calling 调用

require.resolve('./some_module')

gives me exactly what I'm looking for 给了我正是我正在寻找的东西

Here's the only reference I've found in the docs: https://nodejs.org/api/modules.html#modules_all_together 这是我在文档中找到的唯一参考: https//nodejs.org/api/modules.html#modules_all_together

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM