Node.js 如果发生以下情况,fs.existsSync不会在内部等待fs.readFile
我的代码正在运行,但是 代码在ifelse中的fs.readFile完成之前完成Node.js 如果发生以下情况,fs.existsSync不会在内部等待fs.readFile,node.js,fs,Node.js,Fs,我的代码正在运行,但是 代码在ifelse中的fs.readFile完成之前完成 我不知道如何在fs.readFile中添加wait,或者无论如何,正如注释中所写的那样,这段代码正在工作,使用fs,readFileSync将是一个更好的选择 当您使用Array.forEach()时,您正在启动一个同步运行的新函数 我已经清除了你的密码也许这能帮你 if (fs.existsSync('tmp/cache.txt')) { fs.readFile("tmp/cache.t
我不知道如何在fs.readFile中添加wait,或者无论如何,正如注释中所写的那样,这段代码正在工作,使用
fs,readFileSync将是一个更好的选择
当您使用Array.forEach()
时,您正在启动一个同步运行的新函数
我已经清除了你的密码也许这能帮你
if (fs.existsSync('tmp/cache.txt')) {
fs.readFile("tmp/cache.txt", function (err, data) {
if (data != "" || data != "[]") {
jdata = JSON.parse(data);
if (
jdata[jdata.length - 1].substring(4, 8) ==
new Date().getFullYear() + 543
) {
year = new Date().getFullYear() + 542;
console.log("yes this year");
}
jdata.forEach(function (value, i) {
if (
value.substring(4, 8) ==
new Date().getFullYear() + 543
) {
countloveme--;
}
});
jdata.splice(countloveme);
}
});
}
您似乎知道的同步版本存在,但没有,注意到处理一般异步编程可能仍然是一个好主意。fs.readFile()
是非阻塞和异步的,因此您的代码不会等待它完成。如果应用程序中的同步代码正常(例如,它不是服务器),则可以使用fs.readFileSync()
。否则,您需要学习如何在nodejs中编写适当的异步代码,并且我们需要先查看周围的代码上下文,然后才能建议编写此代码的适当方法,因为调用代码也必须更改。
if (fs.existsSync('tmp/cache.txt')) {
try {
const data = fs.readFileSync("tmp/cache.txt");
if (!data || data != "" || data != "[]")
throw new Error('tmp/cache.txt file is empty');
const jdata = JSON.parse(data);
// More clear to use variables in the if elses
const arg1 = jdata[jdata.length - 1].substring(4, 8)
const arg2 = new Date().getFullYear() + 543;
if (arg1 === arg2) {
// You don't use this date anywhere?
new Date().getFullYear() + 542;
console.log("yes this year");
}
for (let dataChunk of jdata) {
if (
dataChunk.substring(4, 8) ==
new Date().getFullYear() + 543
) {
countloveme--;
}
}
jdata.splice(countloveme);
} catch (error) {
console.error(error.message);
}
}