Determine command line working directory when running node bin script

后端 未结 5 585
旧时难觅i
旧时难觅i 2020-12-22 20:34

I am creating a node command line interface. It is installed globally and uses a bin file to execute.

I plan to have a command window open at the root directory of t

相关标签:
5条回答
  • 2020-12-22 20:49

    Alternatively, if you want to solely obtain the current directory of the current NodeJS script, you could try something simple like this. Note that this will not work in the Node CLI itself:

    var fs = require('fs'),
        path = require('path');
    
    var dirString = path.dirname(fs.realpathSync(__filename));
    
    // output example: "/Users/jb/workspace/abtest"
    console.log('directory to start walking...', dirString);
    
    0 讨论(0)
  • 2020-12-22 20:54

    path.resolve('.') is also a reliable and clean option, because we almost always require('path'). It will give you absolute path of the directory from where it is called.

    0 讨论(0)
  • 2020-12-22 20:57

    Current Working Directory

    To get the current working directory, you can use:

    process.cwd()
    

    However, be aware that some scripts, notably gulp, will change the current working directory with process.chdir().

    Node Module Path

    You can get the path of the current module with:

    • __filename
    • __dirname

    Original Directory (where the command was initiated)

    If you are running a script from the command line, and you want the original directory from which the script was run, regardless of what directory the script is currently operating in, you can use:

    process.env.INIT_CWD
    

    Original directory, when working with NPM scripts

    It's sometimes desirable to run an NPM script in the current directory, rather than the root of the project.

    This variable is available inside npm package scripts as:

    $INIT_CWD.
    

    You must be running a recent version of NPM. If this variable is not available, make sure NPM is up to date.

    This will allow you access the current path in your package.json, e.g.:

    scripts: {
      "customScript": "gulp customScript --path $INIT_CWD"
    }
    
    0 讨论(0)
  • 2020-12-22 21:04
    • process.cwd() returns directory where command has been executed (not directory of the node package) if it's has not been changed by 'process.chdir' inside of application.
    • __filename returns absolute path to file where it is placed.
    • __dirname returns absolute path to directory of __filename.

    If you need to load files from your module directory you need to use relative paths.

    require('../lib/test');
    

    instead of

    var lib  = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
    
    require(lib + '/test');
    

    It's always relative to file where it called from and don't depend on current work dir.

    0 讨论(0)
  • 2020-12-22 21:07

    Here's what worked for me:

    console.log(process.mainModule.filename);
    
    0 讨论(0)
提交回复
热议问题