javascript - Can't access app.set variables? -
i creating web app expressjs @ moment.
i want pass port app running on callingscript
module
:
callingscript.js
const http = require('http'); const app = require('./module'); const port = process.env.port || 3000; app.set('port', port); const server = http.createserver(app); // serves correct port, problem passing module.js app.listen(port);
module.js
const express = require('express'); const app = express(); // logs `undefined` console.log(app.get('port')); module.exports = app;
if run above application want see results this:
$ node callingscript.js 3000 $ port=8080 bash -c 'node callingscript.js' 8080
but instead prints undefined
every time.
it looks module.js isn't being passed variable calling script.
how can pass port between two?
you're logging @ wrong time. first module.js
runs, then callingscript.js
runs. console.log
app.get
in module.js
, runs before app.set
in callingscript.js
.
if want configured port in code in module.js
, ensure call code after setting port. instance, here export object both app
, foo
, foo
function:
const express = require('express'); const app = express(); module.exports = { app, foo: function() { console.log("the port " + app.get("port")); } };
then calling it:
const http = require('http'); const m = require('./module'); const port = process.env.port || 3000; m.app.set('port', port); m.foo(); // <==== const server = http.createserver(m.app); // serves correct port, problem passing module.js m.app.listen(port);
that said, sounds might want make module expose function accepts port , returns app
configured use port (along else needs know port is).
Comments
Post a Comment