【发布时间】:2016-06-01 13:04:18
【问题描述】:
我正在做的是使用 fs 将 5 个 html 页面部分(html, head, chead, topaside, main, footer)拼接在一起。文件名是htmlpage.js,所以你可以在命令行工具中运行node htmlpage.js file1 file2 file3 ...,它将那些html页面部分拼接在一起,然后吐出file1.html, file2.html, file3.html ...。我不喜欢使用模板引擎/库/框架之类的东西,尤其是在我学习的时候。
这是源代码:
'use strict';
const fs = require('fs'),
head = fs.createReadStream('./html-parts/head.html', 'utf8'),
topaside = fs.createReadStream('./html-parts/topaside.html', 'utf8'),
footer = fs.createReadStream('./html-parts/footer.html', 'utf8');
let name = process.argv.slice(2),
htmlray = [],
ni = 0,
nl = name.length;
for (ni; ni < nl; ni ++) {
let cheadP = './html-parts/' + name[ni] + '-head.html',
mainP = './html-parts/' + name[ni] + '-main.html',
htmlP = name[ni] + '.html',
chead = fs.createReadStream(cheadP, 'utf8'),
main = fs.createReadStream(mainP, 'utf8'),
html = fs.createWriteStream(htmlP, 'utf8');
//let those parts form an array
htmlray = [html, head, chead, topaside, main, footer];
openendPipe(htmlray[1], htmlray[0]);
htmlray[1].on('end', () => {
openendPipe(htmlray[2], htmlray[0]);
htmlray[2].on('end', () => {
openendPipe(htmlray[3], htmlray[0]);
htmlray[3].on('end', () => {
openendPipe(htmlray[4], htmlray[0]);
htmlray[4].on('end', () => {
htmlray[5].pipe(htmlray[0]);
htmlray[5].on('end', () => {
console.log(name + '.html' + ' created');
});
});
});
});
});
}
function openendPipe(src, dst) {
return src.pipe(dst, {end: false});
}
但是如果 htmlray 有 100 个部分,我希望能够进行迭代以替换这些代码,我们称之为 pipeblock:
openendPipe(htmlray[1], htmlray[0]);
htmlray[1].on('end', () => {
openendPipe(htmlray[2], htmlray[0]);
htmlray[2].on('end', () => {
openendPipe(htmlray[3], htmlray[0]);
htmlray[3].on('end', () => {
openendPipe(htmlray[4], htmlray[0]);
htmlray[4].on('end', () => {
htmlray[5].pipe(htmlray[0]);
htmlray[5].on('end', () => {
console.log(name + '.html' + ' created');
});
});
});
});
});
我尝试了这些解决方案,但没有奏效:
解决方案一:
(function () {
let i = 0, count = 1;
function nextpipe() {
let arr = arguments[0];
i ++;
if (count > 5) return;
openendPipe(arr[i], arr[0]);
count ++;
arr[i].on('end', nextpipe);
}
return nextpipe;
})();
//then replace 'pipeblock' with 'nextpipe(htmlray)';
//console.log: nextpipe is undefined.
解决方案 2:
//replace 'pipeblock' with these code
let pi = 1,
pl = htmlray.length - 1;
htmlray[pi].pipe(htmlray[0], {end: false});
htmlray[pi].on('end', nextpipe);
function nextpipe() {
if (pi > pl) return console.log(name + '.html' + ' created');;
pi ++;
htmlray[pi].pipe(htmlray[0], {end: false});
htmlray[pi].on('end', nextpipe);
}
//cosole.log:
//htmlray[pi].pipe(htmlray[0], {end: false});
//TypeError: Cannot read property 'pipe' of undefined
【问题讨论】:
标签: node.js asynchronous iteration asynccallback