如何在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/。有办法得到那个目录吗?
当前回答
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
});
其他回答
NodeJS公开了一个名为__dirname的全局变量。
__dirname返回JavaScript文件所在文件夹的完整路径。
因此,作为一个例子,对于Windows,如果我们用下面的行创建一个脚本文件:
console.log(__dirname);
然后使用以下命令运行脚本:
node ./innerFolder1/innerFolder2/innerFolder3/index.js
输出将是: C: \用户…<项目目录> \ innerFolder1 \ innerFolder2 \ innerFolder3
这个命令返回当前目录:
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());
});
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;
这将找到当前目录的根目录下的所有文件,要求并导出与文件名干相同的导出名称的每个文件。
你可以使用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));