2

重複の可能性:
module.exports 内の別の関数から module.exports 内の「ローカル」関数を呼び出しますか?

アプリケーションの開発に node.js を使用しています。main.js から別のメソッド内で 1 つのメソッドを呼び出す必要があります。どうすればいいですか?

ここで詳細を説明しています。

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

これどうやってするの?

4

2 に答える 2

4

関数 (メソッド) を変数に割り当てて使用することも、他の .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();
于 2012-12-13T15:36:42.367 に答える