javascript 获取执行 node.js 的目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15149274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:42:03  来源:igfitidea点击:

Getting directory from which node.js was executed

javascriptnode.jspathdirectorypwd

提问by ciembor

I have some project, and I run it with node main.js/ make testetc. What I need is to get this directory from a script. Not only from main.js, but also from any submodule. I tried with pathplugin and __directory, but I get a path of the current file (for example submodule). I also tried require('path').dirname(require.main.filename), but when I run make testI get mocha dirname instead of my project directory. What is the easiest way to solve this?

我有一些项目,我用node main.js/ make testetc运行它。我需要的是从脚本中获取这个目录。不仅来自main.js,还来自任何子模块。我尝试使用pathplugin and __directory,但我得到了当前文件的路径(例如子模块)。我也试过require('path').dirname(require.main.filename),但是当我运行时,make test我得到的是 mocha 目录名而不是我的项目目录。解决这个问题的最简单方法是什么?

回答by JohnnyHK

process.cwd()will provide that.

process.cwd()将提供。

回答by Pascal Belloncle

__dirnamegives you the path where a file resides.

__dirname为您提供文件所在的路径。

回答by Matthew C. Lewis

require.cachestores every loaded module and its associated imported values, parent module, child modules, absolute file path, etc.

require.cache存储每个加载的模块及其关联的导入值、父模块、子模块、绝对文件路径等。

I believe each module is assigned to the cache object using its file path as the cache key, but you will probably want to double check that, just to make sure.

我相信每个模块都使用其文件路径作为缓存键分配给缓存对象,但您可能需要仔细检查,以确保。

If that is the case though, something as simple as Object.keys(require.cache)will give you an array of file paths for all of the modules. Then just parse each path as needed to pull the directory information you are looking for from each module path.

如果是这种情况,那么简单的事情Object.keys(require.cache)就会为您提供所有模块的文件路径数组。然后根据需要解析每个路径,从每个模块路径中提取您要查找的目录信息。

回答by Tahsin Turkoz

Here is a handy function to get access to files provided with relative paths from the console

这是一个方便的功能,可以从控制台访问提供有相对路径的文件

function getPath(filename) {
    return (filename[0] != '/' ? process.cwd() + '/' : "") + filename
}