Shard Shard - 6 months ago 24
Node.js Question

Node.js export both router and function

I'm exporting router at the end of the file and also exporting a function, but I can only get one of them to work at a time.

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


from my main app.js I want to be able to do both:

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

Answer

Any reason why you can't just do this? This seems cleaner than defining a function within exports and trying to call another function within weather.js.

module.exports = { 
  router:router,
  refreshWeather:refreshWeather
}

Then in app.js

var weather = require('./routes/weather.js');
app.use(weather.router)
weather.refreshWeather()

If you don't want to do it that way, try changing exports = router to exports.router = router. Then within app.js you can call weather.router.

Comments