What exactly does "/usr/bin/env node" do at the beginning of node files? Ask Question

What exactly does

I had seen this line #!/usr/bin/env node at the beginning of some examples in nodejs and I had googled without finding any topic that could answer the reason for that line.

The nature of the words makes search it not that easy.

I'd read some javascript and nodejs books recently and I didn't remember seeing it in any of them.

If you want an example, you could see the RabbitMQ official tutorial, they have it in almost all of their examples, here is one of them:

#!/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);
});

Could someone explain me what is the meaning of this line?

What is the difference if I put or remove this line? In what cases do I need it?

ベストアンサー1

#!/usr/bin/env node is an instance of a shebang line: the very first line in an executable plain-text file on Unix-like platforms that tells the system what interpreter to pass that file to for execution, via the command line following the magic #! prefix (called 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]

The following, general discussion of shebang lines is limited to Unix-like platforms:

In the following discussion I'll assume that the file containing source code for execution by Node.js is simply named file.

  • You NEED this line, if you want to invoke a Node.js source file directlyは、それ自体が実行可能ファイルとして機能します。これは、ファイルが などのコマンドで実行可能としてマークされていることを前提としています。chmod +x ./fileこれにより、たとえば でファイルを呼び出すことができます。./fileまた、ファイルが 変数にリストされているディレクトリの 1 つにある場合は$PATH、単に として呼び出すことができますfile

    • 具体的には、シェバンラインを作成する必要がありますCLInpmの一部としてNode.jsソースファイルに基づいているパッケージ、CLIはnpm"bin"パッケージのpackage.jsonファイル内のキー; も参照この答えそれがどのように機能するかについては世界的にインストールされたパッケージ。脚注[1]はWindowsでこれがどのように処理されるかを示しています。
  • あなた必要はありませんこの行は、インタープリタを介してファイルを明示的に呼び出すためのものですnode。例:node ./file


オプションの背景情報:

#!/usr/bin/env <executableName>は、ポータブルインタープリターの指定: 簡単に言うと、変数<executableName>にリストされているディレクトリの中で (最初に) 見つけた場所で実行します$PATH(そして、暗黙的に手元のファイルへのパスを渡します)。

これは、特定のインタープリタがプラットフォーム間で異なる場所にインストールされる可能性があるという事実を説明しています。これはnode、Node.js バイナリの場合に間違いなく当てはまります。

対照的に、ユーティリティ自体の場所envは、同じプラットフォーム間での位置、つまり/usr/bin/env満杯実行ファイルへのパスは必須シェバンラインで。

POSIXユーティリティenv再利用ここでファイル名を指定して実行ファイルを検索し、実行します$PATH
の真の目的はenvコマンドの環境を管理することです。envのPOSIX仕様そしてキース・トンプソンの役に立つ回答


Node.jsが構文を改良していることも注目に値する。例外シェバン行は有効な JavaScript コードではないため、 は#POSIX のようなシェルや他のインタープリターとは異なり、JavaScript ではコメント文字ではありません。


[1] プラットフォーム間の一貫性を保つために、npm作成するラッパー *.cmdWindows 上のファイル (バッチ ファイル)パッケージのpackage.jsonファイルで指定された実行ファイルをインストールするとき(プロパティ経由"bin")。基本的に、これらのラッパーバッチファイルは模倣するUnixのシェバン機能:シェバン行で指定された実行可能ファイルを使用してターゲットファイルを明示的に呼び出す- したがって、スクリプトは、Windows でのみ実行するつもりであっても、シェバン行を含める必要があります。- 見るこの答え詳細については、私の説明を参照してください。ファイルは拡張子なしで呼び出すことができる
ため、シームレスなクロスプラットフォーム エクスペリエンスが実現します。Windows と Unix の両方で、インストールされた CLI を元の拡張子のない名前で効果的に呼び出すことができます。*.cmd.cmdnpm

おすすめ記事