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

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

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

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


当前回答

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

其他回答

如果你想在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;
    }
}
var settings = 
    JSON.parse(
        require('fs').readFileSync(
            require('path').resolve(
                __dirname, 
                'settings.json'),
            'utf8'));

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

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

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

console.log(__dirname);

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

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

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

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

基本上你可以这样做:

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

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

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

require.main.filename

或者,获取文件夹名称:

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