ryanking8215
V2EX  ›  Node.js

node 里有没有类似 python 脚本的 if __name__=='__main__'的功能

  •  
  •   ryanking8215 · Aug 7, 2014 · 4822 views
    This topic created in 4324 days ago, the information mentioned may be changed or developed.
    该功能表示是否是直接执行的脚本还是import来的。
    node下有吗?
    5 replies    2014-08-23 18:08:11 +08:00
    guchengf
        1
    guchengf  
       Aug 7, 2014   ❤️ 1
    var main = function(){
    // main code
    }

    if (require.main === module) {
    main();
    }
    SoloCompany
        2
    SoloCompany  
       Aug 7, 2014
    @guchengf 我的习惯是用 process.mainModule, 然后刚才去查了下文档, 貌似两个用法都不在文档里面
    magicdawn
        3
    magicdawn  
       Aug 8, 2014
    module有parent和childrens属性

    if(module.parent)
    {
    //被require的时候
    }
    xieren58
        5
    xieren58  
       Aug 23, 2014
    if(!module.parent) xxxxxxxxx
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1659 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 16:38 · PVG 00:38 · LAX 09:38 · JFK 12:38
    ♥ Do have faith in what you're doing.