如何使用 Node.js 获取当前脚本的路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3133243/
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
How do I get the path to the current script with Node.js?
提问by Kyle Slattery
How would I get the path to the script in Node.js?
我如何在 Node.js 中获取脚本的路径?
I know there's process.cwd, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/and I run the following command:
我知道有process.cwd,但这仅指调用脚本的目录,而不是脚本本身。例如,假设我在/home/kyle/并运行以下命令:
node /home/kyle/some/dir/file.js
If I call process.cwd(), I get /home/kyle/, not /home/kyle/some/dir/. Is there a way to get that directory?
如果我打电话process.cwd(),我会得到/home/kyle/,不会/home/kyle/some/dir/。有没有办法得到那个目录?
回答by Kyle Slattery
I found it after looking through the documentation again. What I was looking for were the __filenameand __dirnamemodule-level variables.
我再次查看文档后找到了它。我正在寻找的是__filename和__dirname模块级变量。
__filenameis the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js)__dirnameis the directory name of the current module. (ex:/home/kyle/some/dir)
__filename是当前模块的文件名。这是当前模块文件的解析绝对路径。(例如:/home/kyle/some/dir/file.js)__dirname是当前模块的目录名。(例如:/home/kyle/some/dir)
回答by Marc
So basically you can do this:
所以基本上你可以这样做:
fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);
Use resolve() instead of concatenating with '/' or '\' else you will run into cross-platform issues.
使用 resolve() 而不是连接 '/' 或 '\' 否则你会遇到跨平台问题。
Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:
注意:__dirname 是模块或包含脚本的本地路径。如果你正在编写一个需要知道主脚本路径的插件,它是:
require.main.filename
or, to just get the folder name:
或者,只获取文件夹名称:
require('path').dirname(require.main.filename)
回答by Masoud Siahkali
This command returns the current directory:
此命令返回当前目录:
var currentPath = process.cwd();
For example, to use the path to read the file:
例如,要使用路径读取文件:
var fs = require('fs');
fs.readFile(process.cwd() + "\text.txt", function(err, data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
回答by DDD
Use __dirname!!
使用 __dirname !!
__dirname
The directory name of the current module. This the same as the path.dirname() of the __filename.
当前模块的目录名。这与 .dirname() 的 path.dirname() 相同__filename。
Example: running node example.js from /Users/mjr
示例:从 /Users/mjr 运行节点 example.js
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
https://nodejs.org/api/modules.html#modules_dirname
https://nodejs.org/api/modules.html#modules_dirname
For ESModules you would want to use:
import.meta.url
对于 ESModules,您可能需要使用:
import.meta.url
回答by Lukasz Wiktor
When it comes to the main script it's as simple as:
当涉及到主脚本时,它很简单:
process.argv[1]
From the Node.js documentation:
process.argv
An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.
进程.argv
包含命令行参数的数组。第一个元素是 'node',第二个元素是 JavaScript 文件的路径。下一个元素将是任何其他命令行参数。
If you need to know the path of a module file then use __filename.
如果您需要知道模块文件的路径,请使用__filename。
回答by GOTO 0
Node.js 10 supports ECMAScript modules, where __dirnameand __filenameare no longer available.
Node.js 10 支持ECMAScript 模块,其中__dirname和__filename不再可用。
Then to get the path to the current ES moduleone has to use:
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
And for the directory containing the current module:
对于包含当前模块的目录:
import { dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
回答by foobar
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
回答by Hazarapet Tunanyan
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname.
每个 Node.js 程序在其环境中都有一些全局变量,它们表示有关您的进程的一些信息,其中之一是__dirname.
回答by Dana Harris
I know this is pretty old, and the original question I was responding to is marked as duplicate and directed here, but I ran into an issue trying to get jasmine-reporters to work and didn't like the idea that I had to downgrade in order for it to work. I found out that jasmine-reporters wasn't resolving the savePath correctly and was actually putting the reports folder output in jasmine-reporters directory instead of the root directory of where I ran gulp. In order to make this work correctly I ended up using process.env.INIT_CWDto get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
我知道这已经很老了,我回答的原始问题被标记为重复并指向此处,但是我遇到了一个问题,试图让 jasmine-reporters 工作,并且不喜欢我必须降级的想法为了让它工作。我发现 jasmine-reporters 没有正确解析 savePath,实际上是将报告文件夹输出放在 jasmine-reporters 目录中,而不是我运行 gulp 的根目录中。为了使这项工作正常进行,我最终使用process.env.INIT_CWD来获取初始当前工作目录,该目录应该是您运行 gulp 的目录。希望这可以帮助某人。
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
回答by AbiSivam
You can use process.env.PWD to get the current app folder path.
您可以使用 process.env.PWD 获取当前应用程序文件夹路径。

