循环陷阱与闭包
下述是有问题的代码,因为nodejs的执行是异步的
var fs = require('fs');
var files = ['a.txt', 'b.txt', 'c.txt'];
for (var i = 0; i < files.length; i++) {//这里有了变化
fs.readFile(files[i], 'utf-8', function (err, contents) {
console.log(files[i] + ': ' + contents);
});
}
优化修复:
var fs = require('fs');
var files = ['a.txt', 'b.txt', 'c.txt'];
files.forEach(function (filename) {//这里有了变化
fs.readFile(filename, 'utf-8', function (err, contents) {
console.log(filename + ': ' + contents);
});
});
复杂一点的逐行读取:
const puppeteer = require('puppeteer');
var readline = require('readline');
var fs = require('fs');
var os = require('os');
var fReadName = './a.txt';
var fRead = fs.createReadStream(fReadName);
fRead.on('end', ()=>{
console.log('end');
enableWriteIndex = false;
});
var objReadline = readline.createInterface({
input: fRead,
terminal: true
});
var index = 1;
objReadline.on('line', (line)=>{
(async () => {
console.log(index, line);
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(line);
await page.screenshot({path:index+'qq.png'});
browser.close();
await index ++;
}
)();
});
objReadline.on('close', ()=>{
console.log('readline close...');
});