imperium2335
imperium2335

Reputation: 24112

Using functions inside scripts required by NodeJS's required()

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

Upvotes: 0

Views: 127

Answers (3)

sachin
sachin

Reputation: 14355

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

Upvotes: 0

loxxy
loxxy

Reputation: 13151

It's called exporting a module.

Sample from here :

create a file ./utils.js, and define the merge() function as seen below..

  function merge(obj, other) {

      //...
  };

  exports.merge = merge;

Now the merge function is accessible another JS in utils as:

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

utils.merge();

Upvotes: 0

freakish
freakish

Reputation: 56467

If it is not a part of module.exports then you can't. For example:

web-notification.js

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

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

main-js.js

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

Upvotes: 2

Related Questions