零零乙
2010-06-28 14:31
采纳率: 50%
浏览 452
已采纳

如何使用 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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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)
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • lrony* 2011-09-08 18:40

    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)
    
    评论
    解决 无用
    打赏 举报
  • elliott.david 2015-12-17 10:41

    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.

    评论
    解决 无用
    打赏 举报
  • 斗士狗 2016-05-25 21:27

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

    评论
    解决 无用
    打赏 举报
  • 叼花硬汉 2016-09-28 07:00

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

    评论
    解决 无用
    打赏 举报
  • derek5. 2016-10-23 07:17

    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());
    });
    
    评论
    解决 无用
    打赏 举报
  • 乱世@小熊 2017-03-15 15:37

    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>
    
    评论
    解决 无用
    打赏 举报
  • 撒拉嘿哟木头 2017-05-05 09:32

    If you want something more like $0 in a shell script, try this:

    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;
        }
    }
    
    评论
    解决 无用
    打赏 举报
  • larry*wei 2017-09-08 07:28

    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.

    评论
    解决 无用
    打赏 举报
  • perhaps? 2017-12-22 14:30

    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

    评论
    解决 无用
    打赏 举报
  • Didn"t forge 2018-02-09 19:29

    Another approach, if you're using modules and you'd like to find the filename of the main module that called such sub-module or any module you're running, is to use

    var fnArr = (process.mainModule.filename).split('/');
    var filename = fnArr[fnArr.length -1];
    
    评论
    解决 无用
    打赏 举报
  • larry*wei 2018-04-27 01:01

    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);
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题