nodejs fs.exists (fs.access) 在for循环中发生了奇怪的事情

nodejs fs.exists (fs.access) has strange things happen in for-loop

我的代码:

for(var i=0; i<2; i++)
{
    console.log("idx: " + i);

    fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
      console.log(err ? 'no access!'+i : 'can read/write'+i);
    });

    fs.exists('/etc/passwd', (exists) => {
      console.log(exists ? 'it\'s there'+i : 'no passwd!'+i);
    });
}

结果:
idx: 0
idx: 1
无法访问!2
在那里2
无法访问!2
在那里2

为什么 i =2?
我该如何解决?

你的问题的关键是异步。 fs的两个方法都是异步的,后面会执行,执行的时候i的值为2,因为循环结束了。

最简单的解决方法是通过 let

改变循环变量的声明
for(let i=0; i<2; i++)

它将 i 的范围限制为一次迭代

fs.access and fs.exists 是异步调用,当他们执行回调时,由于循环,累加器已经设置为 2。