【问题标题】:How can you determine if a Coffeescript script is being run as a script vs being required in a module?如何确定 Coffeescript 脚本是作为脚本运行还是在模块中需要?
【发布时间】:2015-01-07 18:36:37
【问题描述】:

我有一个咖啡脚本文件,其中包含我希望其他脚本需要的代码,但我也希望它作为独立脚本运行。

确定另一个脚本是否需要它还是直接运行它的最可靠方法是什么?

例如 要求(“./myScript.coffee”) 对比 咖啡./myScript.coffee

【问题讨论】:

    标签: javascript process coffeescript


    【解决方案1】:

    这是在节点上吗?如果是这样,这里有两个选项

    A) 使用调用堆栈

    stack = new Error().stack
    

    B) 使用 require.cache

    检查您的脚本是否在 require.cache 列表中。例如here 是一个单元测试,它在当前的 require.cache 上找到一个特定的脚本,并将其删除

        for file in require.cache.keys()
          if file.contains(['node/server.coffee']) or  file.contains(['node-cov/server.coffee'])
            pathToApp = file
            break
    
        require.cache[pathToApp].assert_Is_Object()
        delete require.cache[pathToApp]
    
        app = require '../server'
    

    【讨论】:

      【解决方案2】:

      我目前的解决方案是在“独立脚本执行”之前包含此行逻辑检查

      if process.argv[1].toString().indexOf('myScript.coffee') != -1
          # Standalone script code here
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-06
        • 2010-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-21
        相关资源
        最近更新 更多