Shard Shard - 1 year ago 93
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();

// Refresh weather...

exports = router; // It's either this
exports.refresh = function() { // or this.
console.log('Done refreshing');

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

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 Source

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 = { 

Then in app.js

var weather = require('./routes/weather.js');

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download