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

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

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

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


当前回答

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

其他回答

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

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

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

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

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

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