How to access a value inside the callback from the global scope?

Viewed 46

I'm using express Js and I want to export the port on which the server is running for some testing purpose. But the port seems to be only available inside callback function of app.listen.Is there any way I can export the port?

let server = app.listen(3000, 'localhost', ()=>{
let port = server.address().port;
})
// accesss port here
module.export = port; // what I want
2 Answers

You could put a Promise as the export which resolves to the port:

module.exports.portProm = new Promise((resolve) => {
  const server = app.listen(3000, 'localhost', () => {
    resolve(server.address().port);
  });
});

and do

require('server.js').portProm.then((port) => {
  // use port here
});

Since the first parameter is the port the server should listen to, why not just pass a specific port in the first place?

const port = 3042;
let server = app.listen(port, 'localhost');

module.exports = port;

edit

~~Defining the variable outside the callback should do the trick:~~

It doesn't, because the app resolves asynchronously.

let port;

let server = app.listen(3000, 'localhost', () => {
    port = server.address().port;
});

// accesss port here
module.exports = port;
Related