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:
我知道过程。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/。有办法得到那个目录吗?
13 个解决方案
#1
995
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
我又看了一遍文件才找到它。我要找的是__filename和__dirname模块级变量。
#2
183
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)
#3
46
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());
});
#4
35
Use __dirname!!
使用__dirname ! !
__dirname
The directory name of the current module. This the same as the path.dirname() of the __filename
.
当前模块的目录名。这与__filename的路径.dirname()相同。
Example: running node example.js from /Users/mjr
示例:运行节点的例子。js /用户/ mjr
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
#5
33
When it comes to the main script it's as simple as:
当涉及到主要脚本时,它很简单:
process.argv[1]
From the Node.js documentation:
从节点。js文件:
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.
包含命令行参数的数组。第一个元素是“node”,第二个元素是JavaScript文件的路径。下一个元素将是任何附加的命令行参数。
If you need to know the path of a module file then use __filename.
如果您需要知道模块文件的路径,请使用__filename。
#6
26
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
#7
24
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname
.
每一个节点。js程序在其环境中有一些全局变量,这些变量表示关于进程的一些信息,其中之一是__dirname。
#8
9
You can use process.env.PWD to get the current app folder path.
您可以使用process.env。获取当前应用程序文件夹路径的PWD。
#9
5
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_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
我知道这是一个相当古老的问题,我最初的问题被标记为重复和指向这里,但我遇到了一个问题,试图让jasmin -reporter工作,不喜欢我不得不降级以使它工作。我发现jasmin -reporter没有正确地解析savePath,实际上将reports文件夹输出放在jasmin -reporter目录中,而不是我运行gulp的根目录中。为了正确地完成这项工作,我最后使用了process.env。init_wd获取初始的当前工作目录,该目录应该是您运行gulp的目录。希望这可以帮助别人。
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
#10
3
Node.js 10 supports ECMAScript modules, where __dirname
and __filename
are not available out of the box.
节点。js 10支持ECMAScript模块,其中没有现成的__dirname和__filename。
Then to get the path to the current ES module one has to use:
然后,要获得当前ES模块的路径,必须使用:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
对于包含当前模块的目录:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
#11
-1
If you want something more like $0 in a shell script, try this:
如果您想在shell脚本中使用$0之类的东西,请尝试以下操作:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
#12
-1
If you are using pkg
to package your app, you'll find useful this expression:
如果您正在使用pkg来打包应用程序,您会发现这个表达式非常有用:
appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
-
process.pkg
tells if the app has been packaged bypkg
.的过程。pkg告诉我们应用程序是否已经被pkg打包。
-
process.execPath
holds the full path of the executable, which is/usr/bin/node
or similar for direct invocations of scripts (node test.js
), or the packaged app.的过程。execPath保存了可执行文件的完整路径,它是/usr/bin/node,或者类似于直接调用脚本(node test.js),或者打包的应用程序。
-
require.main.filename
holds the full path of the main script, but it's empty when Node runs in interactive mode.require.main。filename包含主脚本的完整路径,但是当Node在交互模式下运行时,它是空的。
-
__dirname
holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better useappDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0]));
noting that in interactive mode__dirname
is empty.__dirname拥有当前脚本的完整路径,因此我不使用它(尽管它可能是OP所要求的;然后最好使用appDirectory = process。包裹吗?require('path').dirname(process.execPath): (__dirname || require('path').dirname(process.argv[0]);注意在交互模式下__dirname是空的。
-
For interactive mode, use either
process.argv[0]
to get the path to the Node executable orprocess.cwd()
to get the current directory.对于交互模式,可以使用任何一个过程。argv[0]获取到节点可执行文件或process.cwd()的路径,以获取当前目录。
#13
-1
Another approach, if you're using modules and you'd like to find the filename of the main module that called such sub-module or any module you're running, is to use
另一种方法是,如果您正在使用模块,并且您希望找到称为此类子模块或正在运行的任何模块的主模块的文件名
var fnArr = (process.mainModule.filename).split('/');
var filename = fnArr[fnArr.length -1];
#1
995
I found it after looking through the documentation again. What I was looking for were the __filename
and __dirname
module-level variables.
我又看了一遍文件才找到它。我要找的是__filename和__dirname模块级变量。
#2
183
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)
#3
46
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());
});
#4
35
Use __dirname!!
使用__dirname ! !
__dirname
The directory name of the current module. This the same as the path.dirname() of the __filename
.
当前模块的目录名。这与__filename的路径.dirname()相同。
Example: running node example.js from /Users/mjr
示例:运行节点的例子。js /用户/ mjr
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
#5
33
When it comes to the main script it's as simple as:
当涉及到主要脚本时,它很简单:
process.argv[1]
From the Node.js documentation:
从节点。js文件:
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.
包含命令行参数的数组。第一个元素是“node”,第二个元素是JavaScript文件的路径。下一个元素将是任何附加的命令行参数。
If you need to know the path of a module file then use __filename.
如果您需要知道模块文件的路径,请使用__filename。
#6
26
var settings =
JSON.parse(
require('fs').readFileSync(
require('path').resolve(
__dirname,
'settings.json'),
'utf8'));
#7
24
Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname
.
每一个节点。js程序在其环境中有一些全局变量,这些变量表示关于进程的一些信息,其中之一是__dirname。
#8
9
You can use process.env.PWD to get the current app folder path.
您可以使用process.env。获取当前应用程序文件夹路径的PWD。
#9
5
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_CWD to get the initial Current Working Directory which should be the directory where you ran gulp. Hope this helps someone.
我知道这是一个相当古老的问题,我最初的问题被标记为重复和指向这里,但我遇到了一个问题,试图让jasmin -reporter工作,不喜欢我不得不降级以使它工作。我发现jasmin -reporter没有正确地解析savePath,实际上将reports文件夹输出放在jasmin -reporter目录中,而不是我运行gulp的根目录中。为了正确地完成这项工作,我最后使用了process.env。init_wd获取初始的当前工作目录,该目录应该是您运行gulp的目录。希望这可以帮助别人。
var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
savePath: process.env.INIT_CWD + '/report/e2e/',
consolidateAll: true,
captureStdout: true
});
#10
3
Node.js 10 supports ECMAScript modules, where __dirname
and __filename
are not available out of the box.
节点。js 10支持ECMAScript模块,其中没有现成的__dirname和__filename。
Then to get the path to the current ES module one has to use:
然后,要获得当前ES模块的路径,必须使用:
const __filename = new URL(import.meta.url).pathname;
And for the directory containing the current module:
对于包含当前模块的目录:
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
#11
-1
If you want something more like $0 in a shell script, try this:
如果您想在shell脚本中使用$0之类的东西,请尝试以下操作:
var path = require('path');
var command = getCurrentScriptPath();
console.log(`Usage: ${command} <foo> <bar>`);
function getCurrentScriptPath () {
// Relative path from current working directory to the location of this script
var pathToScript = path.relative(process.cwd(), __filename);
// Check if current working dir is the same as the script
if (process.cwd() === __dirname) {
// E.g. "./foobar.js"
return '.' + path.sep + pathToScript;
} else {
// E.g. "foo/bar/baz.js"
return pathToScript;
}
}
#12
-1
If you are using pkg
to package your app, you'll find useful this expression:
如果您正在使用pkg来打包应用程序,您会发现这个表达式非常有用:
appDirectory = require('path').dirname(process.pkg ? process.execPath : (require.main ? require.main.filename : process.argv[0]));
-
process.pkg
tells if the app has been packaged bypkg
.的过程。pkg告诉我们应用程序是否已经被pkg打包。
-
process.execPath
holds the full path of the executable, which is/usr/bin/node
or similar for direct invocations of scripts (node test.js
), or the packaged app.的过程。execPath保存了可执行文件的完整路径,它是/usr/bin/node,或者类似于直接调用脚本(node test.js),或者打包的应用程序。
-
require.main.filename
holds the full path of the main script, but it's empty when Node runs in interactive mode.require.main。filename包含主脚本的完整路径,但是当Node在交互模式下运行时,它是空的。
-
__dirname
holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better useappDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0]));
noting that in interactive mode__dirname
is empty.__dirname拥有当前脚本的完整路径,因此我不使用它(尽管它可能是OP所要求的;然后最好使用appDirectory = process。包裹吗?require('path').dirname(process.execPath): (__dirname || require('path').dirname(process.argv[0]);注意在交互模式下__dirname是空的。
-
For interactive mode, use either
process.argv[0]
to get the path to the Node executable orprocess.cwd()
to get the current directory.对于交互模式,可以使用任何一个过程。argv[0]获取到节点可执行文件或process.cwd()的路径,以获取当前目录。
#13
-1
Another approach, if you're using modules and you'd like to find the filename of the main module that called such sub-module or any module you're running, is to use
另一种方法是,如果您正在使用模块,并且您希望找到称为此类子模块或正在运行的任何模块的主模块的文件名
var fnArr = (process.mainModule.filename).split('/');
var filename = fnArr[fnArr.length -1];