2

In app.js I have a function I want to call from a routes file.

This is simplified of course.

app.js

var express = require('express');
var app = express();

var foo = function() {
  return 'bar';
}

module.exports = app;

index.js

?

I tried to require('../app.js') and call app.foo but that didn't work.

6
  • What are you trying to accomplish? Commented Jul 16, 2015 at 15:44
  • Are you trying to call foo from outside app.js? What you have at the moment is a module that exports an instance of express... Commented Jul 16, 2015 at 15:44
  • @Tholle I open a sqlite database in app.js and want to have a function on the server that performs queries and returns the results on a route call. Commented Jul 16, 2015 at 15:46
  • @James yeah call foo from outside app.js Commented Jul 16, 2015 at 15:47
  • 1
    @Tholle never thought of that. I'm new to all this. Ill give that a shot Commented Jul 16, 2015 at 15:49

1 Answer 1

3

If you want to export both app and foo then you could export an object surfacing both

module.exports = {
    app: app,
    foo: foo
}

Or alternatively, you could do

module.exports.app = app;
module.exports.foo = foo;

Then in your routes

var app = require('../app').app,
    foo = require('../app').foo;
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks, now how would I call foo in the routes? foo( );?
@NorCalKnockOut yes, the module exports the function foo from the app.js file so you would just call it like any normal function.
I keep getting undefined is not a function for foo();
Do you actually have a function called foo in app.js?
Yeah, var foo = function() { return 'bar'; }
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.