node.js - 无法等待 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
. 当我明确要求它在继续之前等待时,这怎么可能?
解决方案
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
推荐阅读
- list - 打印文本中出现频率最高的值
- java - 如何使用 POI 在给定段落之前插入 sdt?
- java - 休眠映射异常错误:未知实体
- ruby-on-rails - 单个外键引用多个表 [Rails6]
- python - SQLAlchemy - 如何序列化自动加载的模型?
- heroku - 在 heroku 上部署一个 MERN 应用程序,带有两个单独的文件夹
- html - 在 Flutter 中的 iOS 上 WebView 显示太小和最小化
- javascript - 在名为 Mumbling 的 Codewars 任务的解决方案中找到正确的正则表达式的问题
- c# - 反斜杠的可变长度后视
- html - 未捕获的 TypeError:非法调用。尝试在 Nodejs 中使用 ajax 发帖时