Detect if called through require or directly by command line

后端 未结 5 1030
南方客
南方客 2020-11-30 16:26

How can I detect whether my Node.JS file was called using SH:node path-to-file or JS:require(\'path-to-file\')?

This is the Node.JS equival

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 17:02

    I was a little confused by the terminology used in the explanation(s). So I had to do a couple quick tests.

    I found that these produce the same results:

    var isCLI = !module.parent;
    var isCLI = require.main === module;
    

    And for the other confused people (and to answer the question directly):

    var isCLI = require.main === module;
    var wasRequired = !isCLI;
    

提交回复
热议问题