如何在Node.js中获取脚本的路径?
我知道有流程。Cwd,但它只引用调用脚本的目录,而不是脚本本身。例如,假设我在/home/kyle/目录下,然后运行以下命令:
node /home/kyle/some/dir/file.js
如果我调用process.cwd(),我会得到/home/kyle/,而不是/home/kyle/some/dir/。有办法得到那个目录吗?
如何在Node.js中获取脚本的路径?
我知道有流程。Cwd,但它只引用调用脚本的目录,而不是脚本本身。例如,假设我在/home/kyle/目录下,然后运行以下命令:
node /home/kyle/some/dir/file.js
如果我调用process.cwd(),我会得到/home/kyle/,而不是/home/kyle/some/dir/。有办法得到那个目录吗?
当前回答
使用__dirname ! !
__dirname
当前模块的目录名。这与__filename的path.dirname()相同。
例如:在/Users/mjr中运行node Example .js
console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
https://nodejs.org/api/modules.html#modules_dirname
对于esmodule,你会想要使用: import.meta.url
其他回答
Node.js 10支持ECMAScript模块,其中__dirname和__filename不再可用。
然后,要获得当前ES模块的路径,必须使用:
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
对于包含当前模块的目录:
import { dirname } from 'path';
import { fileURLToPath } from 'url';
const __dirname = dirname(fileURLToPath(import.meta.url));
每个Node.js程序在其环境中都有一些全局变量,这些变量表示关于进程的一些信息,其中一个是__dirname。
你可以使用process.env.PWD来获取当前应用程序的文件夹路径。
这个命令返回当前目录:
var currentPath = process.cwd();
例如,使用路径读取文件:
var fs = require('fs');
fs.readFile(process.cwd() + "\\text.txt", function(err, data)
{
if(err)
console.log(err)
else
console.log(data.toString());
});
如果你使用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 by 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. require.main.filename holds the full path of the main script, but it's empty when Node runs in interactive mode. __dirname holds the full path of the current script, so I'm not using it (although it may be what OP asks; then better use appDirectory = process.pkg ? require('path').dirname(process.execPath) : (__dirname || require('path').dirname(process.argv[0])); noting that in interactive mode __dirname is empty. For interactive mode, use either process.argv[0] to get the path to the Node executable or process.cwd() to get the current directory.