Node Js:如何在服务器启动时异步执行函数

Node Js: how to execute functions async in the start of the server

我想运行导出文件中的函数作为应用程序中的第一个函数(异步方式)。

此函数必须在 运行 连接服务器时首先执行,并且会询问我们是本地环境还是生产环境!

该函数在配置文件中:

//config/config.js:

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
module.exports= function(next) {
    console.log("call fi,n");
    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();
        console.log("asnwerere");
        next();
    },next);

}


//app.js:
app.use(function(next){
    require('./config/config')(next);
}); 

现在第一个问题是这个函数不是运行在服务器启动时而是在接收HTTP请求的时候

所以问题是如何以异步方式使此功能 运行ning :作为应用程序的第一个功能(必须阻止服务器,直到我引入此功能中提到的命令行)?

这个函数签名

app.use(function(next){...});

错了。应该是:

app.use(function(req, res, next){...});

所以,因为你的函数参数错误,你使用了错误的东西作为 next,当有人试图调用它时会得到一个错误。

因此,在您的代码中更改为:

//app.js:
app.use(function(next){
    require('./config/config')(next);
}); 

对此:

//app.js:
app.use(function(req, res, next){
    require('./config/config')(next);
});