V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ryanking8215
V2EX  ›  Node.js

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

  •  
  •   ryanking8215 · 2014-08-07 14:55:17 +08:00 · 3965 次点击
    这是一个创建于 3540 天前的主题,其中的信息可能已经有所发展或是发生改变。
    该功能表示是否是直接执行的脚本还是import来的。
    node下有吗?
    5 条回复    2014-08-23 18:08:11 +08:00
    guchengf
        1
    guchengf  
       2014-08-07 14:57:31 +08:00   ❤️ 1
    var main = function(){
    // main code
    }

    if (require.main === module) {
    main();
    }
    SoloCompany
        2
    SoloCompany  
       2014-08-07 22:28:23 +08:00
    @guchengf 我的习惯是用 process.mainModule, 然后刚才去查了下文档, 貌似两个用法都不在文档里面
    magicdawn
        3
    magicdawn  
       2014-08-08 06:29:14 +08:00
    module有parent和childrens属性

    if(module.parent)
    {
    //被require的时候
    }
    ibudao
        4
    ibudao  
       2014-08-08 11:17:00 +08:00
    xieren58
        5
    xieren58  
       2014-08-23 18:08:11 +08:00
    if(!module.parent) xxxxxxxxx
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1515 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:05 · PVG 01:05 · LAX 10:05 · JFK 13:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.