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

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

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

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


当前回答

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;

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

其他回答

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

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

你可以使用process.env.PWD来获取当前应用程序的文件夹路径。

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));

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

每个Node.js程序在其环境中都有一些全局变量,这些变量表示关于进程的一些信息,其中一个是__dirname。