节点文件开头的“/usr/bin/env node”到底做什么?

2023-11-27

我见过这条线#!/usr/bin/env node在一些例子的开头nodejs我用谷歌搜索没有找到任何可以回答该行原因的主题。

单词的性质使得搜索变得不那么容易。

我读过一些javascript and nodejs最近读的书,我不记得在任何一本书中看到过它。

如果你想要一个例子,你可以看到RabbitMQ官方的tutorial,他们几乎所有的例子都有它,这是其中之一:

#!/usr/bin/env node

var amqp = require('amqplib/callback_api');

amqp.connect('amqp://localhost', function(err, conn) {
  conn.createChannel(function(err, ch) {
    var ex = 'logs';
    var msg = process.argv.slice(2).join(' ') || 'Hello World!';

    ch.assertExchange(ex, 'fanout', {durable: false});
    ch.publish(ex, '', new Buffer(msg));
    console.log(" [x] Sent %s", msg);
  });

  setTimeout(function() { conn.close(); process.exit(0) }, 500);
});

有人能给我解释一下这行的含义是什么吗?

如果我添加或删除此行有什么区别?什么情况下我需要它?


#!/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.

  • You 需要这条线,如果你想调用 Node.js 源文件directly,作为其本身的可执行文件 - 这假设该文件已使用以下命令标记为可执行文件chmod +x ./file,然后您可以使用以下命令调用该文件:./file,或者,如果它位于列出的目录之一中$PATH变量,简单地说file.

    • 具体来说,您需要一个 shebang 线来创建CLIs基于作为 npm 一部分的 Node.js 源文件package,其中要安装的 CLInpm基于的价值"bin"包中的密钥package.json file;另见这个答案了解它如何与globally安装的软件包。脚注 [1] 显示了 Windows 上的处理方式。
  • You 不需要此行通过显式调用文件node口译员,例如node ./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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

节点文件开头的“/usr/bin/env node”到底做什么? 的相关文章

随机推荐