2017-10-09 60 views
0

我期待下面的代碼打印出來Node.js的fs.WriteStream的行爲出現異常

Finished writing GB translations 
Finished writing DE translations 
Finished writing US translations 

而是將其打印出來

Finished writing DE translations 
Finished writing DE translations 
Finished writing DE translations 

代碼:

try { 
    fs.mkdirSync('./locales'); 
} catch(e) { 
    console.log('Info: Locales directory already exists'); 
} 

jsonDefs = { 
      GB: {"Item does not exist": "Item does not exist"}, 
      DE: {"Item does not exist": "Artikel existiert nicht"}, 
      US: {"Item does not exist": "Item does naaht exist"} 
      }; 

for(language in jsonDefs){ 
    const fileName = `${language.toLowerCase()}.json`; 
    const writeStream = fs.createWriteStream(`./locales/${fileName}`); 
    writeStream.on('finish', function(){ console.log(`Finished writing ${language} translations`); }); 
    writeStream.on('error', function(err){ 
     console.log(`Error writing to ${fileName}: ${err}`); 
    }); 
    writeStream.write(JSON.stringify(jsonDefs[language]),() => writeStream.end()); 
} 

除如預期,雖然它似乎很好地工作,一切都被寫入gb.json,de.json和us.json。爲什麼是這樣?

回答

1

language每次都在for循環中被覆蓋,但.on('finish'異步執行。所以language = 'DE'有效地發生第一,那麼所有的'finish'事件發生所以它會打印出什麼'language'設置爲持續。

有很多的方法來解決這個問題,但最簡單的/一個需要改變最少的是隻使用let,如:

for (let language in jsonDefs) { 

這將範圍language爲每次迭代循環。當然

+0

啊,經典的'''var'''錯誤,感謝指出了這一點 – Nodeocrat