如何在Node.js中获取脚本的路径?

我知道有流程。Cwd,但它只引用调用脚本的目录,而不是脚本本身。例如,假设我在/home/kyle/目录下,然后运行以下命令:

node /home/kyle/some/dir/file.js

如果我调用process.cwd(),我会得到/home/kyle/,而不是/home/kyle/some/dir/。有办法得到那个目录吗?


我又看了一遍文件后找到的。我要找的是__filename和__dirname模块级变量。

__filename是当前模块的文件名。这是当前模块文件的解析绝对路径。(例:/ home /凯尔/一些/ dir / file.js) __dirname是当前模块的目录名。(例:/ home /凯尔/一些/ dir)


基本上你可以这样做:

fs.readFile(path.resolve(__dirname, 'settings.json'), 'UTF-8', callback);

使用resolve()而不是连接'/'或'\',否则您将遇到跨平台问题。

注意:__dirname是模块或包含脚本的本地路径。如果你正在编写一个插件,需要知道主脚本的路径,它是:

require.main.filename

或者,获取文件夹名称:

require('path').dirname(require.main.filename)

var settings = 
    JSON.parse(
        require('fs').readFileSync(
            require('path').resolve(
                __dirname, 
                'settings.json'),
            'utf8'));

当涉及到主脚本时,它非常简单:

process.argv[1]

来自Node.js文档:

process.argv 包含命令行参数的数组。第一个元素是“node”,第二个元素是JavaScript文件的路径。下一个元素将是任何额外的命令行参数。

如果你需要知道模块文件的路径,那么使用__filename。


每个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());
});

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.

var reporters = require('jasmine-reporters');
var junitReporter = new reporters.JUnitXmlReporter({
  savePath: process.env.INIT_CWD + '/report/e2e/',
  consolidateAll: true,
  captureStdout: true
 });

如果你想在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;
    }
}

如果你使用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.


使用__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));

使用path模块的basename方法:

var path = require('path');
var filename = path.basename(__filename);
console.log(filename);

下面是上面例子的文档。

正如Dan指出的,Node正在处理带有“——experimental-modules”标志的ECMAScript模块。节点12仍然支持前面提到的__dirname和__filename。


如果您正在使用——experimental-modules标志,还有另一种方法。

另一种方法是获取当前ES模块的路径:

import { fileURLToPath } from 'url';
const __filename = fileURLToPath(new URL(import.meta.url));

对于包含当前模块的目录:

import { fileURLToPath } from 'url';
import path from 'path';

const __dirname = path.dirname(fileURLToPath(new URL(import.meta.url)));

Index.js中包含要导出的模块的任何文件夹

const entries = {};
for (const aFile of require('fs').readdirSync(__dirname, { withFileTypes: true }).filter(ent => ent.isFile() && ent.name !== 'index.js')) {
  const [ name, suffix ] = aFile.name.split('.');
  entries[name] = require(`./${aFile.name}`);
}

module.exports = entries;

这将找到当前目录的根目录下的所有文件,要求并导出与文件名干相同的导出名称的每个文件。


NodeJS公开了一个名为__dirname的全局变量。

__dirname返回JavaScript文件所在文件夹的完整路径。

因此,作为一个例子,对于Windows,如果我们用下面的行创建一个脚本文件:

console.log(__dirname);

然后使用以下命令运行脚本:

node ./innerFolder1/innerFolder2/innerFolder3/index.js

输出将是: C: \用户…<项目目录> \ innerFolder1 \ innerFolder2 \ innerFolder3