2

Possible Duplicate:
Call a “local” function within module.exports from another function in module.exports?

I am using node.js for develop my application. I have to call one method within another method from my main.js. how do i do this?

i am explaining detail here.

app.js

app.post('/getNotificationCount', function (req, res) {
    res.setHeader('Cache-Control', 'max-age=0, must-revalidate, no-cache, no-store');
    res.setHeader('Connection', 'keep-alive');
    res.contentType('application/json');
    res.setHeader('Expires', new Date().addYears(-10));
    try {
          //here i have my custom code/logic
          //i have to call '/getNotification' method here, i have to pass parameter too..
    }
    catch (err) {
        console.log('\r\n ' + new Date().toString() + ' - Try Catch from /getNotificationCount : ' + err + ' \r\n ');
        res.json({ error: 'Forbidden' }, 403);
    }
});

app.post('/getNotification', function (req, res) {
    res.setHeader('Cache-Control', 'max-age=0, must-revalidate, no-cache, no-store');
    res.setHeader('Connection', 'keep-alive');
    res.contentType('application/json');
    res.setHeader('Expires', new Date().addYears(-10));
    try {
          //my sql code goes here !!!
          //I want retrieve parameter in req.body here...
    }
    catch (err) {
        console.log('\r\n ' + new Date().toString() + ' - Try Catch from /getNotification : ' + err + ' \r\n ');
        res.json({ error: 'Forbidden' }, 403);
    }
});

How can i do this?

Community
  • 1
  • 1
Manish Sapkal
  • 5,591
  • 8
  • 45
  • 74

2 Answers2

4

You can assign the function (method) to a variable and use that, also you can export your functions in other .js scripts.

export.js

exports.moduleFunction = function(param) {
    console.log(param);
}

main.js

// Import your module
var myModule = require('./export');

var myFunction = function(param) {
    console.log(param);
};

var main = function mainFunction() {
    // Call function in this same script
    myFunction('hello world!');
    // Call from module
    myModule.moduleFunction('Hello world from module export');
};

main();
E. Celis
  • 717
  • 7
  • 17
0

use module.exports concept..

to get an idea i am giving two links posted here.. Node JS - Calling a method from another method in same file

Call a "local" function within module.exports from another function in module.exports?

hope you will get an idea..

Community
  • 1
  • 1
Rinku
  • 1,078
  • 6
  • 11