如何使用 Node.js 获得当前脚本的路径?

How would I get the path to the script in Node.js?

I know there's process.cwd, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in /home/kyle/ and I run the following command:

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

If I call process.cwd(), I get /home/kyle/, not /home/kyle/some/dir/. Is there a way to get that directory?

转载于:https://stackoverflow.com/questions/3133243/how-do-i-get-the-path-to-the-current-script-with-node-js

csdnceshi75
衫裤跑路 nodejs.org/docs/latest/api/globals.html the documentation link of the accepted answer.
7 年多之前 回复

12个回答

I found it after looking through the documentation again. What I was looking for were the __filename and __dirname module-level variables.

  • __filename is the file name of the current module. This is the resolved absolute path of the current module file. (ex:/home/kyle/some/dir/file.js)
  • __dirname is the directory name of the current module. (ex:/home/kyle/some/dir)
csdnceshi51
旧行李 If you're using webpack: path.dirname(process.mainModule.filename)
大约 3 年之前 回复
csdnceshi73
喵-见缝插针 Slattery, can you please tell more about module-level variables
接近 4 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 FYI: Neither of these will work within the interactive node console, but do within scripts.
4 年多之前 回复
csdnceshi52
妄徒之命 comment is definitely the best solution to this.
4 年多之前 回复
csdnceshi75
衫裤跑路 Or require('path').basename(__dirname);
接近 5 年之前 回复
csdnceshi54
hurriedly% Or simply __dirname.split(path.sep).pop()
5 年多之前 回复
csdnceshi59
ℙℕℤℝ Found it: var parts = pathString.split(path.sep); return parts[parts.length - 1] (github.com/joyent/node/issues/1224)
5 年多之前 回复
csdnceshi59
ℙℕℤℝ For those trying @apx solution (like I did:), this solution does not work on Windows.
5 年多之前 回复
weixin_41568208
北城已荒凉 __dirname.split("/").pop()
6 年多之前 回复
csdnceshi63
elliott.david If you want only the directory name and not the full path, you might do something like this: function getCurrentDirectoryName() { var fullPath = __dirname; var path = fullPath.split('/'); var cwd = path[path.length-1]; return cwd; }
接近 7 年之前 回复

So basically you can do this:

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

Use resolve() instead of concatenating with '/' or '\' else you will run into cross-platform issues.

Note: __dirname is the local path of the module or included script. If you are writing a plugin which needs to know the path of the main script it is:

require.main.filename

or, to just get the folder name:

require('path').dirname(require.main.filename)
csdnceshi54
hurriedly% Node V8: path.dirname(process.mainModule.filename)
大约 3 年之前 回复
csdnceshi57
perhaps? Thanks! For a while now I was hacking my way around the fact that __dirname is local to each module. I have a nested structure in my library and need to know in several places the root of my app. Glad I know how to do this now :D
7 年多之前 回复
csdnceshi67
bug^君 If your goal is just to parse and interact with the json file, you can often do this more easily via var settings = require('./settings.json'). Of course, it's synchronous fs IO, so don't do it at run-time, but at startup time it's fine, and once it's loaded, it'll be cached.
8 年多之前 回复

Every Node.js program has some global variables in its environment, which represents some information about your process and one of it is __dirname.

If you are using pkg to package your app, you'll find useful this expression:

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.

csdnceshi68
local-host Exactly what I was looking for, thanks.
大约 2 年之前 回复

You can use process.env.PWD to get the current app folder path.

csdnceshi64
游.程 OP asks for the requested "path to the script". PWD, which stands for something like Process Working Directory, is not that. Also, the "current app" phrasing is misleading.
大约 3 年之前 回复

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

</div>

Use __dirname!!

__dirname

The directory name of the current module. This the same as the path.dirname() of the __filename.

Example: running node example.js from /Users/mjr

console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr

https://nodejs.org/api/modules.html#modules_dirname

csdnceshi56
lrony* This survives symlinks too. So if you create a bin and need to find a file, eg path.join(__dirname, "../example.json"); it will still work when your binary is linked in node_modules/.bin
2 年多之前 回复

When it comes to the main script it's as simple as:

process.argv[1]

From the Node.js documentation:

process.argv

An array containing the command line arguments. The first element will be 'node', the second element will be the path to the JavaScript file. The next elements will be any additional command line arguments.

If you need to know the path of a module file then use __filename.

csdnceshi75
衫裤跑路 If main script was launched with a node process manager like pm2 process.argv[1] will point to the executable of the process manager /usr/local/lib/node_modules/pm2/lib/ProcessContainerFork.js
3 年多之前 回复
csdnceshi68
local-host Not good when you think about testing.
大约 4 年之前 回复
csdnceshi52
妄徒之命 Maybe because process.argv[1] applies only to the main script while __filename points to the module file being executed. I update my answer to emphasize the difference. Still, I see nothing wrong in using process.argv[1]. Depends on one's requirements.
4 年多之前 回复
csdnceshi67
bug^君 Could the downvoter please explain why this is not recommended?
4 年多之前 回复

Node.js 10 supports ECMAScript modules, where __dirname and __filename are not available out of the box.

Then to get the path to the current ES module one has to use:

const __filename = new URL(import.meta.url).pathname;

And for the directory containing the current module:

import path from 'path';

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

This command returns the current directory:

var currentPath = process.cwd();

For example, to use the path to read the file:

var fs = require('fs');
fs.readFile(process.cwd() + "\\text.txt", function(err, data)
{
    if(err)
        console.log(err)
    else
        console.log(data.toString());
});
csdnceshi70
笑故挽风 Current directory is a very different thing. If you run something like cd /foo; node bar/test.js, current directory would be /foo, but the script is located in /foo/bar/test.js.
大约 2 年之前 回复
csdnceshi61
derek5. this is exactly what the OP doesn't want... the request is for the path of the executable script!
2 年多之前 回复
csdnceshi63
elliott.david For those who didn't understand Asynchronous and Synchronous, see this link... stackoverflow.com/a/748235/5287072
3 年多之前 回复
共12条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐