#!/usr/bin/env node
is 的一个实例舍邦线: the 可执行纯文本文件中的第一行类 Unix 平台告诉系统将该文件传递给哪个解释器来执行,通过命令行跟随魔法#!
前缀(称为shebang).
Note: Windows does not support shebang lines, so they're effectively ignored there; on Windows it is solely a given file's filename extension that determines what executable will interpret it. However, you still need them in the context of npm
.[1]
下列,舍邦线的一般讨论仅限于类 Unix 平台:
In the following discussion I'll assume that the file containing source code for execution by Node.js is simply named file
.
可选背景信息:
#!/usr/bin/env <executableName>
是一种方式portably指定解释器:简而言之,它表示:执行<executableName>
无论您(第一次)在列出的目录中找到它$PATH
变量(并隐式地将其传递到手头文件的路径)。
这说明了一个事实,即给定的解释器可能跨平台安装在不同的位置,这绝对是这种情况node
,Node.js 二进制文件。
相比之下,env
实用程序本身可以信赖same跨平台位置,即/usr/bin/env
- 并指定full可执行文件的路径是required在 Shebang 线上。
请注意 POSIX 实用程序env
正在改变用途在这里按文件名定位并执行可执行文件$PATH
.
真正的目的是env
是管理命令的环境 - 请参阅env的 POSIX 规范 and 基思·汤普森的有用回答.
还值得注意的是 Node.js 正在制定语法例外对于 shebang 行,因为它们不是有效的 JavaScript 代码(#
与类似 POSIX 的 shell 和其他解释器不同,它不是 JavaScript 中的注释字符)。
[1] In the interest of cross-platform consistency, npm
creates wrapper *.cmd
files (batch files) on Windows when installing executables specified in a package's package.json
file (via the "bin"
property). Essentially, these wrapper batch files mimic Unix shebang functionality: they invoke the target file explicitly with the executable specified in the shebang line - thus, your scripts must include a shebang line even if you only ever intend to run them on Windows - see this answer of mine for details.
Since *.cmd
files can be invoked without the .cmd
extension, this makes for a seamless cross-platform experience: on both Windows and Unix you can effectively invoke an npm
-installed CLI by its original, extension-less name.