I am trying to understand what is going on when I use module.exports with a variable in a model view controller type project. I just do not understand what the book means by using it in this way
var express = require("./config/express.js");
var app = express();
app.listen(3000);
module.exports = app; // my problem is right here what is it doing
console.log("Server running at http://localhost:3000/");
my config/ express file is also here
var express = require("express");
module.exports = function()
{
var app = express();
require("../app/routes/index.server.routes.js")(app);
return app;
}
The first example is exporting the Express app directly and the second example is exporting a function that returns the Express app.
This means that in the first example, require(...) will return app. In the second example, you would need to do require(...)() to have app returned.
Related
I have a app.js
const express = require('express');
const app = express();
const server = require('./server.js');
// app.use
const io = require('socket.io').listen(server);
io.on('connection', function (socket) {
...
});
module.exports = app;
And a server.js
const app = require('./app');
const server = app.listen(5000 || process.env.PORT, () => {
console.log('App listening on port 5000!');
})
module.exports = server;
If I put the server in a separated file the socket is not working, but if I start the server inside the app.js the socket works.
What I'm doing wrong?
The issue here is that you have a circular dependency where app.js is loading server.js and server.js is loading app.js. You can't do that for this type of code.
It has an issue because you're trying to load server.js from within app.js and then in the process of loading server.js, it attempts to load app.js and get its exports, but app.js hasn't finished loading yet and thus hasn't even returned its exports yet. So, the loader either thinks there are no exports or recognizes the circular request (I'm not sure which), but in either case the exports from app.js don't work because of the circular requires.
There are several different ways to solve this. The two most common ways are:
Break some code into a common third module that each of these can load and only have one of these load the other.
Rather than having server.js load app to get the app object, have app.js pass the app object to server.js in a constructor function rather than trying to execute at module load time.
Here's how the constructor function idea would work:
app.js
const express = require('express');
const app = express();
// load server.js and call it's constructor, passing the app object
// that module constructor function will return the server object
const server = require('./server.js')(app);
// app.use
const io = require('socket.io').listen(server);
io.on('connection', function (socket) {
...
});
module.exports = app;
server.js
// export constructor function that must be called to initialize this module
module.exports = function(app) {
const server = app.listen(5000 || process.env.PORT, () => {
console.log('App listening on port 5000!');
});
return server;
};
So, rather than server.js trying to load the app.js module to get the app object, the app object is "pushed" to it with a constructor function. This prevents the circular dependency.
Can someone explain in depth what does this line of code mean in NodeJS:
var app = module.exports = express.createServer();
express.createServer();
The above line has the instance of express and creates a server instance (server handle) and returns the whole export class.
With the above, you are setting both module.exports as well as app to do further.
It can be rewritten as:
module.exports = express.createServer();
var app = module.exports;
I have a node project and something very strange is happening. I have a routes file that has all of my routes and I import that on my server.js file. When I import the routes file. A get request of that route does not work at all, but when I paste that same route on the server.js it works as expected. Other routes in the file work correctly, but this one in particular does not work as expected. Code below. Thanks for any help.
server.js
require('./server/routes/mainRoutes.js')(app);
mainRoutes (this will not work):
app.get('/accounts',function(req,res){
res.json({Test:'name'});
});
Now if I put that /accounts route on the main server.js it will work. For some reason it never works in the imported mainRoutes file.
I'm not sure why it's not working, It can help if you share the app initiation (I understand you use express?) and your use of app.listen.
Anyway, a best practice would be to use app.use, as follows:
server.js:
var routes = require('./server/routes/mainRoutes.js');
var express = require('express');
var app = express();
app.use('/', routes.app);
var server = app.listen(somePort, someIP, function() {
console.log('Listening...');
});
mainRoutes.js:
var express = require('express');
var app = express();
app.get('/accounts',function(req,res){
res.json({Test:'name'});
});
module.exports = {
app: app
};
In an attempt to build a truly modular express app (one that can run stand alone or as a part of another app) I need to find out the cleanest way to find the mount path from inside the subapp. For a short example, lets say that there are two files: main.js and subapp.js
main.js
var express = require('express');
var app = express();
var localApp = express();
var subapp = require('./subapp');
app.use('/foo', subapp);
app.use('/bar', localApp);
console.log(localApp.mountpath); // yes, this prints '/bar' as expected
...
subapp.js
var express = require('express');
var app = express();
var truePath = app.mountpath; // I wish this would point to '/foo', but instead points to '/'
...
module.exports = app;
What is the best way (as in cleanest) to find the mountpath from inside the module? I'm doing this trying to solve this problem: Access to mountpath variable from inside a template using express in a non hardwired way.
As shown in the example, tried already with app.mountpath without success
As answered by alsotang, this is actually a problem of execution sequence, but it can be solved in what I think is a clean way. There is an event that is fired after the module is mounted, so you can do:
var truePath = = "/";
app.on('mount', function (parent) {
truePath = app.mountpath;
});
Where in real life truePath could be app.locals.truePath, so it can be accessed from inside the views.
eh..It's a problem of execution sequence.
In your subapp.js, the app.mountpath statement is before module.exports = app.
But only you export the app, then the app be mounted, then it would be set the mountpath property.
so, you should retrieve mountpath after the app be mounted by outer express.
My suggestion are two:
set the mountpath in your subapp.js. And outer express read this property.
perhaps you think 1 is not truly modular. so you can alternatively define a config file. and both main.js and subapp.js read mountpath from the config.
Try req.baseUrl:
app.js
var express = require('express');
var app = express();
var foo = require('./foo');
app.use('/foo', foo);
app.listen(3000);
foo.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
console.log(req.baseUrl); // '/foo'
res.send('foo');
});
module.exports = router;
I have an ExpressJS application that uses several routers. Here is the basic form of the main app that ties everything together.
var express = require('express');
var routes = require('./routes/index');
var app = express();
app.set('someKey', someObj);
app.use('/', routes);
module.exports = app;
I have removed most of the code for brevity.
In that ./routes/index.js file I have defined a Express Router in the form:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index', { title: 'Express Test' });
});
module.exports = router;
I have attempted to use the following to access "somekey" from inside the router:
var app = require('../app');
var foo = app.get('somekey');
This crashes and burns with the runtime informing me that there is no such method get for app (further investigation yields that app is just a default Object).
I assume I am overlooking something that is completely obvious.
I plan to be passing a single knexjs object to each of the routers that deal with database calls. In the code's current state it is duplicated across each of the routers. I'd like to have it defined once in the main app and then be used by all of the routers such that if a change is made in the main app it is reflected across the routers.
When you require the app that way, you are not exactly referring to the app object you defined in your app.js. Instead, you are asking for whatever that file exported. To get what you want to achieve, may use something like this.
In your app.js
var express = require('express');
var app = express(); // Note the switched order
app.set('someKey', someObj);
var routes = require('./routes/index')(app);
app.use('/', routes);
module.exports = app;
Then in your routes:
var express = require('express');
var router = express.Router();
/* Wrap everything inside a function */
module.exports = function(app){
console.log(app.get('someKey')); // Access app passed to it from app.js
/* Declare all your routes here. app variable will be accessible */
router.get('/', function(req, res) {
res.render('index', { title: 'Express Test' });
});
return router;
};
Basically, whenever you are requiring a file B from A and want to pass a variable from A to B, this is the general pattern you follow.
See if if helps. :)