javascripting javascripting - 3 years ago 138
Javascript Question

How to correctly export and require in node js?

I read a tutorial about export/require in node/express and wonder if someone could explain to me with my example:
why is my routing in app.js not working? What would I have to export and require to make it work? Thanks a lot!

index.js:

'use strict'

var express = require('express');

var app = express();
module.exports = app;

var PORT = process.env.PORT || 1337;
app.listen(PORT, function() {
console.log('Server is listening!');
})


app.js:

var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
//var app=require('./index.js');
module.exports = function() {
app.use(express.static(path.join(__dirname, '../public')));
app.use(express.static(path.join(__dirname, '../browser')));
}

Answer Source
  1. Your example will not work correctly at least because you declared two separate express servers in both files var app = express().
  2. This code is not the most suitable for practice in exporting/requiring because such servers initializations are usually placed in one file.

But anyway, if you would like to use this example and make it work, let's do in in this way:

./ index.js

'use strict'

var express = require('express');
var setupServing = require('./setupServing.js'); //import our function
var PORT = process.env.PORT || 1337;

var app = express(); //create express app
setupServing(app); //call imported function to config our app

app.listen(PORT, function() { //start
    console.log('Server is listening!');
})

./ setupServing.js

var express = require('express');
var path = require('path');
//export function which can configure static serve for app
module.exports = function(app) { //take app as an argument
    app.use(express.static(path.join(__dirname, '../public')));
}

Note that this example still is not logical enough and I don't think you will face such code in any real project, but anyway it will work and demonstrate exporting/requiring in nodejs.

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