Detect if called through require or directly by command line

后端 未结 5 1019
南方客
南方客 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:26

    There is another, slightly shorter way (not outlined in the mentioned docs).

    var runningAsScript = !module.parent;

    I outlined more details about how this all works under the hood in this blog post.

提交回复
热议问题