Node.js导出路由器和函数

i34xakig  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(75)

我在文件的末尾导出router,同时也导出一个函数,但我一次只能让其中一个函数工作。

// 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
sqserrrh

sqserrrh1#

为什么你不能这么做?这似乎比在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。

相关问题