动态调用节点中导出的函数

时间:2015-05-13 13:44:06

标签: node.js

我是节点新手并逐渐学习 我的 app.js 文件是服务器, app_functions.js 包含我的所有应用功能

var express = require('express');
var app_functions = require ('./app_functions');
var app = express();

app.get('/', function (req, res) {  
 res.send('Running NODE!');
});

// Ex: when I request http://ip.address:3000/functionOne
app.get('/:method', function (req, res) {
// I want to call function that "method" holds i.e, in this case 'functionOne'
// and that function will reside in app_functions.js
});

var server = app.listen(3000, function () {
  console.log('Server listening');
});

当它们在同一个文件中时,我能够使用global []调用这些函数。

我的 app_functions.js 就像这样

exports.functionOne = function functionOne() {
return "functionOne executed";
};

exports.functionTwo = function functionTwo() {
return "functionTwo executed";
};

请帮帮我。提前谢谢。

1 个答案:

答案 0 :(得分:2)

没有问题。只需获取对象的属性,然后使用()执行它。示例(此处我还检查属性是否为函数):

var express = require('express');
var app_functions = require('./app_functions');
var app = express();

app.get('/', function(req, res) {
    res.send('Running NODE!');
});

// Ex: when I request http://ip.address:3000/functionOne
app.get('/:method', function(req, res) {
    // I want to call function that "method" holds i.e, in this case 'functionOne'
    // and that function will reside in app_functions.js
    if (typeof app_functions[req.params.method] === 'function') {
        app_functions[req.params.method]();
    }
});

var server = app.listen(3000, function() {
    console.log('Server listening');
});