Nodejs文件存在
如果我尝试检查只存在一个文件(其实存在),我的testing通过成功。 但是,如果我尝试添加断言不存在的文件,这两个testing通过错误
describe('script entry points', function () { entryJs = { "app": "./coffee/app", "shame": "./coffee/shame" }; for(var pointJs in entryJs) { pathJs = 'web/js'+pointJs+'.js'; it('should return true when '+pathJs+' file exist', function () { fs.stat(pathJs, function(err, data) { if (err) console.log('it does not exist'); else console.log('it exists'); }); }); } });
添加console.log(pathJs);
就在fs.stat
之前,你会发现fs.stat
被调用两次,具有相同的pathJs
值。
在第一次调用fs.stat的时候,pathJsvariables在last 循环中保存了分配给它的值。
原因是node.js的asynchronous性质。 你需要使用闭包。
解:
for(var pointJs in entryJs) { pathJs = 'web/js/'+entryJs[pointJs]+'.js'; (function(path){ it('should return true when '+path+' file exist', function () { fs.stat(path, function(err, data) { if (err) console.log('it does not exist'); else console.log('it exists'); }); }); })(pathJs); }