Reputation: 85
I want to execute inst1 before inst2 in app.js :
// config/config.js
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
module.exports= function() {
console.log("config.js function");
rl.question('Run in production environnement (Y|N) ?', (answer) => {
if(answer === "Y")
process.env.NODE_ENV = 'prod';
else
process.env.NODE_ENV = 'dev';
rl.close();
});
}
//app.js
const express = require('express');
const app=express();
// inst 1
require('./config/config')();
// inst 2
app.listen(port,()=>{
console.log(`server started on port ${port}`);
});
So as you see here, my function in config.js waits to read a console input. So I want that the app.listen(..) waits until the previous instruction which is my function ends.
How can I proceed ?
Upvotes: 0
Views: 43
Reputation: 138457
Promisify your first function:
module.exports = new Promise(res => {
console.log("config.js function");
rl.question('Run in production environnement (Y|N) ?', res);
}).then(answer => {
process.env.NODE_ENV = "Y" ? 'prod' : 'dev';
rl.close();
});
So you can do this in app.js
:
const express = require('express');
const app = express();
(async function(){
await require('./config/config');
app.listen(port, () => {
console.log(`server started on port ${port}`);
});
})();
Upvotes: 1