我在文件末尾导出路由器并导出一个函数,但我一次只能让其中一个工作。
// weather.js
var express = require('express');
var router = express.Router();
refreshWeather(){
// Refresh weather...
}
exports = router; // It's either this
exports.refresh = function() { // or this.
refreshWeather();
console.log('Done refreshing');
};
来自我的主app.js我希望能够做到这两点:
//app.js
var express = require('express');
var app = express();
var weather = require('./routes/weather.js');
app.use(weather) // I want to be able to use this for routing
weather.refresh(); // But also be able to call refresh function of weather.js
答案 0 :(得分:14)
为什么你不能这样做?这似乎比在exports中定义函数并尝试在weather.js中调用另一个函数更简洁。
module.exports = {
router:router,
refreshWeather:refreshWeather
}
然后在app.js
var weather = require('./routes/weather.js');
app.use(weather.router)
weather.refreshWeather()
如果您不想这样做,请尝试将exports = router更改为exports.router = router。然后在app.js中你可以调用weather.router。