首页 > 解决方案 > 无法等待 fs.appendFile

问题描述

我正在尝试在启动 Nodejs 服务器之前检查是否存在所有必需的环境变量,如果缺少一些或所有变量,则终止 Nodejs。

所以我有一个名为checkVariables.js

const writeFile = util.promisify(fs.appendFile)

checkDBState()

async function checkDBState(){
    try{
        dbState = process.env.dbState
        if(!dbState){
            console.log(`dbState not Found in the .env file`)
            console.log(`Terminating Server`)
            await errorLogOnFile(`dbState not Found in the .env file`)
            return false
         }
         return true
    }
    catch(err){
        console.log(err)
    }
}

async function errorLogOnFile(errorMessage){
    try{
        let currentDate = new Date()

        let dateTime = currentDate.getMonth()+1 + "/"
        + (currentDate.getDate()+1)  + "/" 
        + currentDate.getFullYear() + " @ "  
        + currentDate.getHours() + ":"  
        + currentDate.getMinutes() + ":" 
        + currentDate.getSeconds(); 
    
        errorMessage = `\n${dateTime} - ${errorMessage} `
        
        await writeFile('errorLog.txt',errorMessage)
        process.exit(1);
        // fs.appendFileSync('errorLog.txt',errorMessage,(err)=>{
        //     if(err) throw err;
        //     process.exit(1);
        // })
    }
    catch(err){
        console.log(err)
    } 
   
   
}

我看到的问题是代码没有等待写入文件,而其他一些模块在进程写入文件时运行。因此,在服务器终止之前,我在其他文件上遇到了一些错误。我使用了调试器,发现整个过程是同步的,直到达到writeFile. 当我明确要求它在继续之前等待时,这怎么可能?

标签: node.js

解决方案


Ciao, what do you think about this solution?

async function checkDBState() {
   dbState = process.env.dbState;
   if(!dbState){
     await new Promise((resolve) => {
        let currentDate = new Date();

        let dateTime = currentDate.getMonth()+1 + "/"
        + (currentDate.getDate()+1)  + "/" 
        + currentDate.getFullYear() + " @ "  
        + currentDate.getHours() + ":"  
        + currentDate.getMinutes() + ":" 
        + currentDate.getSeconds(); 

        errorMessage = `\n${dateTime} - ${errorMessage} `;
        fs.appendFileSync('errorLog.txt',errorMessage);
        resolve(console.log('file written'));        
     });
  }
  console.log('this happens after file is written');
}

checkDBState();

The output will be (if(!dbState) === true):

file written
this happens after file is written

And in the end a golden rule that helped me thousand times: Async/Await only works on functions that return (and resolve) a promise


推荐阅读