如何从另一个方法调用一个方法

可能重复:
从module.exports中的另一个函数调用module.exports中的“本地”函数?

我正在使用node.js来开发我的应用程序。 我必须从我的main.js调用另一个方法中的一个方法。 我该怎么做呢?

我在这里解释细节。

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

我怎样才能做到这一点?

您可以将函数(方法)分配给一个variables并使用它,也可以将其他.js脚本中的函数导出。

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

使用module.exports概念

得到一个想法,我给这里张贴两个链接。 节点的JS – 调用另一种方法在同一个文件中的方法

从module.exports中的另一个函数调用module.exports中的“本地”函数?

希望你能明白..