LoginSignup
1
0

More than 5 years have passed since last update.

NodeJSで、requireされたのか、単体で起動されたのか判断する方法

Posted at

expressで、テスト用にappインスタンスだけ取得したいけど、app.listenを同じファイルに書きたいって!!いう状況に陥った。

(app.jsbin/wwwみたいに分けるのがベストっぽいけど、あまり好きじゃない。)

require.mainmoduleで判別

requireされ、モジュールとして動いてるときは、require.main !== module

単体で起動されているときは、require.main === moduleとなる。

コード化

sample.js
if (require.main === module) {
  console.log('直接起動されたよ!');
} else {
  console.log('requireされて、モジュールとして動いてるよ!');
}
1
0
0

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
1
0