LoginSignup
20
21

More than 1 year has passed since last update.

[Node.js] モジュールとして読み込まれたのか直接実行されたのか判定する

Last updated at Posted at 2014-11-12

require.main === module でそのスクリプトがモジュールとして読み込まれたのか、直接 Node から実行されたのかを判定できるようだ。

module.exports = function () {};

if (require.main === module) {
    // 直接実行された場合実行される
    console.log("this is not module.");
} else {
    // モジュールとして読み込まれた場合実行される
    console.log("this is module.");
}

これがわかると例えば Express の app オブジェクトをデーモン化するツールに渡した場合と直接実行した場合の両方でうまく実行することができる。

var express = require("express");
var app = module.exports = express();

....

if (require.main === module) {
    app.listen(3000);
}

使いどころがありそうなので覚えておきたい。

20
21
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
21