题:读取若干个文件并将文件中的内容拼串
- async串行读取
const async = require('async');
const fs = require('fs');
let files = ['01.txt', '02.txt', '03.txt']
let arr = [];
let str = '';
for (let index = 0; index < files.length; index++) {
arr[index] = function(callback) {
fs.readFile('../data/' + files[index], (err, data) => {
if (err) {
// console.error('errMsg: ' + err);
callback(`read files[${index}] -> readFile ${files[index]} wrong!`, str);
} else {
str += data;
callback(null);
}
});
};
}
async.waterfall(arr, (err, result) => {
if (err) {
console.log(err);
console.log('result: ' + result);
return;
}
console.log('result: ' + str);
});
- async并行读取
const async = require('async');
const fs = require('fs');
let files = ['01.txt', '02.txt', '03.txt'];
let arr = []; //存函数
let all = []; //存数据
for (let index = 0; index < files.length; index++) {
arr[index] = function(callback) {
fs.readFile('../data/' + files[index], (err, data) => {
if (err) {
console.error('errMsg: ' + err);
}
all[index] = data;
callback(null,data);
});
};
}
async.parallel(arr,(err)=>{
if (err) {
console.log(err);
}
console.log('result:'+all.toString());
});
- Promise并行读取
const fs = require('fs');
const files = ['01.txt', '02.txt', '03.txt', '04.txt'];
const arr = [];
const all = [];
for (let index = 0; index < files.length; index++) {
arr[index] =
new Promise((resolve, reject) => {
fs.readFile('../data/' + files[index], (err, data) => {
if (err) {
reject(`read ${files[index]} error`);
}
all[index] = data;
resolve();
});
});
}
Promise.all(arr).then(() => {
console.log(all.join(''));
});