循环陷阱与闭包

下述是有问题的代码,因为nodejs的执行是异步的

  1. var fs = require('fs');
  2. var files = ['a.txt', 'b.txt', 'c.txt'];
  3.  
  4. for (var i = 0; i < files.length; i++) {//这里有了变化
  5.   fs.readFile(files[i], 'utf-8', function (err, contents) {
  6.   console.log(files[i] + ': ' + contents);
  7.   
  8. });
  9. }

优化修复:

  1. var fs = require('fs');
  2. var files = ['a.txt', 'b.txt', 'c.txt'];
  3. files.forEach(function (filename) {//这里有了变化
  4.   fs.readFile(filename, 'utf-8', function (err, contents) {
  5.   console.log(filename + ': ' + contents);
  6. });
  7. });

复杂一点的逐行读取:

  1. const puppeteer = require('puppeteer');
  2. var readline = require('readline');
  3. var fs = require('fs');
  4. var os = require('os');
  5. var fReadName = './a.txt';
  6. var fRead = fs.createReadStream(fReadName);
  7. fRead.on('end', ()=>{
  8. console.log('end');
  9. enableWriteIndex = false;
  10. });
  11. var objReadline = readline.createInterface({
  12. input: fRead,
  13. terminal: true
  14. });
  15. var index = 1;
  16. objReadline.on('line', (line)=>{
  17. (async () => {
  18. console.log(index, line);
  19. const browser = await puppeteer.launch();
  20. const page = await browser.newPage();
  21. await page.goto(line);
  22. await page.screenshot({path:index+'qq.png'});
  23. browser.close();
  24. await index ++;
  25. }
  26. )();
  27. });
  28. objReadline.on('close', ()=>{
  29. console.log('readline close...');
  30. });