0

How do you access a function that is inside one of the scripts that you have "included" using Node's require() function?

--main-js.js--

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

--web-notification.js--

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

Also how would I use this function in other required scripts?


--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);
}
4

3 回答 3

2

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

网络通知.js

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

module.exports = exports = {
    getURL: getURL
};

main-js.js

var webnotis = require('./modules/web-notification.js');
webnotis.getURL(...);
于 2013-07-17T08:57:47.070 回答
0

这称为导出模块。

来自这里的样本:

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

  function merge(obj, other) {

      //...
  };

  exports.merge = merge;

现在合并功能可以访问另一个JS utils

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

utils.merge();
于 2013-07-17T09:00:11.500 回答
0
   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);
            }

      });

网络通知.js

     exports.getURL=function(host, path,cb) {
            var url=host+path;
             cb(null,url);
     }
于 2013-07-17T09:06:48.773 回答