【问题标题】:Using functions inside scripts required by NodeJS's required()在 NodeJS 的 required() 所需的脚本中使用函数
【发布时间】:2013-07-15 17:49:00
【问题描述】:

如何使用 Node 的 require() 函数访问您“包含”的脚本之一中的函数?

--main-js.js--

var webnotis = require('./modules/web-notification.js')

--web-notification.js--

function getURL(host, path) {
...
}

另外,我将如何在其他必需的脚本中使用此功能?


--report-tables.js--

var cltvOut;
exports.cltv = function cltv(getURL)
{
  clearTimeout(cltvOut);
  cltvOut = setTimeout(function(){
    if(exports.getURL('192.168.0.15', '/IMS4/Reports/calculateCLTV'))
    {
      cltv();
    } else {
      console.log('CLTV error.')
    }
  }, 2000);
}

webnotis2 = require('./web-notification.js')
var cltvOut;
exports.cltv = function cltv()
{
  clearTimeout(cltvOut);
  cltvOut = setTimeout(function(){
    if(webnotis2.getUrl('192.168.0.15', '/IMS4/Reports/calculateCLTV'))
    {
      cltv();
    } else {
      console.log('CLTV error.')
    }
  }, 2000);
}

【问题讨论】:

    标签: javascript node.js function require


    【解决方案1】:
       var webnotis = require('./modules/web-notification.js')
          var host='urhost';
          var path='urpath'; 
          webnotis.getURL(host,path,function(err,res){
             if(!err){
                   console.log('url is '+res);
                }
    
          });
    

    web-notification.js

         exports.getURL=function(host, path,cb) {
                var url=host+path;
                 cb(null,url);
         }
    

    【讨论】:

      【解决方案2】:

      这叫做导出模块。

      来自here 的示例:

      创建一个文件 ./utils.js,并定义 merge() 函数,如下所示..

        function merge(obj, other) {
      
            //...
        };
      
        exports.merge = merge;
      

      现在可以通过utils中的另一个JS访问合并功能:

      var utils = require('./utils');
      
      utils.merge();
      

      【讨论】:

        【解决方案3】:

        如果它不是module.exports 的一部分,那么你不能。例如:

        web-notification.js

        function getURL(host, path) {
        ...
        }
        
        module.exports = exports = {
            getURL: getURL
        };
        

        ma​​in-js.js

        var webnotis = require('./modules/web-notification.js');
        webnotis.getURL(...);
        

        【讨论】:

        • 我已经尝试过了,但是当我尝试在另一个模块中访问它时,它告诉我该对象不存在。请参阅编辑。
        • @imperium2335:如果函数是由另一个模块定义和导出的,你不能通过exports.getURL访问它。 exports 只保存应该由 current 模块导出的值。您必须通过分配模块的变量来访问它,就像他的回答中显示的怪异一样。也许你应该再看看模块是如何工作的:nodejs.org/api/modules.html.
        • @FelixKling 我已经阅读了它和示例,但是当我从另一个模块中调用它时它不起作用。
        • @imperium2335:在 web-notification.js 中,您必须执行 exports.getURL = getURL;,而在 main-js.js 中,您必须执行 webnotis.getURL(...)。而已。如果这不起作用,那么您的模块无法加载,因为您提供了错误的文件路径,或者您的模块中有错误,或者您确实做了不同的事情。除了展示它是如何完成的之外,我们无能为力。
        • @FelixKling 但是我必须在 report-tables.js 中做什么?这也是 main-js.js 中需要的一个模块。
        猜你喜欢
        • 1970-01-01
        • 2013-08-21
        • 2013-03-25
        • 2016-04-11
        • 2012-09-13
        • 1970-01-01
        • 1970-01-01
        • 2021-09-06
        • 2020-05-29
        相关资源
        最近更新 更多