node.js 运行 node bin 脚本时确定命令行工作目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12238477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:15:44  来源:igfitidea点击:

Determine command line working directory when running node bin script

node.jscommand-linenpm

提问by Daniel Chatfield

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

我正在创建一个节点命令行界面。它是全局安装的,并使用一个 bin 文件来执行。

I plan to have a command window open at the root directory of the files I am working on and then just run the command however I have been unable to determine the current working directory as process.cwd()is returning the directory of the node package. I initially assumed that since the code is being executed using a batch file as a wrapper (that is how bin files can execute without node at the beginning) then it is impossible but coffee-script manages to do it. I took a look at the coffee-script source but couldn't follow it (not experienced enough).

我计划在我正在处理的文件的根目录下打开一个命令窗口,然后只运行该命令,但是我无法确定当前工作目录,因为process.cwd()它返回节点包的目录。我最初假设,由于代码是使用批处理文件作为包装器执行的(这就是 bin 文件可以在没有节点的情况下在开始时执行的方式),所以这是不可能的,但 coffee-script 设法做到了。我查看了 coffee-script 源代码,但无法理解(经验不足)。

To test it for yourself create a package with this package.json file:

要自己测试,请使用此 package.json 文件创建一个包:

{
  "name": "test-package",
  "version": "1.0.0",
  "bin": {
    "test-package":  "./bin/test-package"
  },
  "main": "/lib/test"
}

this test-package file in bin:

bin中的这个测试包文件:

#!/usr/bin/env node

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

require(lib + '/test');

Could anyone shed some light onto this.

任何人都可以对此有所了解。

and then try and get the command line directory inside lib/test.

然后尝试获取 lib/test 中的命令行目录。

回答by Vadim Baryshev

  • 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.
  • __filenamereturns absolute path to file where it is placed.
  • __dirnamereturns absolute path to directory of __filename.
  • process.cwd()如果应用程序内部的“process.chdir”没有更改命令,则返回已执行命令的目录(不是节点包的目录)。
  • __filename返回放置文件的绝对路径。
  • __dirname返回目录的绝对路径__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.

它总是相对于它调用的文件,不依赖于当前的工作目录。

回答by superluminary

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().

但是,请注意某些脚本,尤其是 gulp,会使用process.chdir().

Node Module Path

节点模块路径

You can get the path of the current module with:

您可以通过以下方式获取当前模块的路径:

  • __filename
  • __dirname
  • __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

使用 NPM 脚本时的原始目录

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

有时需要在当前目录而不是项目的根目录中运行 NPM 脚本。

This variable is available inside npm package scripts as:

此变量在 npm 包脚本中可用,如下所示:

$INIT_CWD.

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

您必须运行最新版本的 NPM。如果此变量不可用,请确保 NPM 是最新的。

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

这将允许您访问 package.json 中的当前路径,例如:

scripts: {
  "customScript": "gulp customScript --path $INIT_CWD"
}

回答by John Paul Barbagallo

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:

或者,如果您只想获取当前 NodeJS 脚本的当前目录,您可以尝试这样的简单操作。请注意,这在 Node CLI 本身中不起作用:

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

回答by sziraqui

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.

path.resolve('.')也是一个可靠和干净的选择,因为我们几乎总是require('path'). 它将为您提供调用它的目录的绝对路径。