http.createServer(function(req, res) {
var theFile;
res.write('hello');
theFile = fs.createReadStream('./file.txt');
theFile.on('end', function() {
return res.end('world');
});
return theFile.pipe(res);
}).listen(3001);
以下是我重写的:
var app=koa();
app.use(function*(next){
this.body = 'hello'
this.body += fs.createReadStream('./file.txt')
this.body += 'world'
})
app.listen(3000)
但运行结果不符合预期,
重写代码中我不想用 fs.readFile 代替 stream。
很简单,先把createReadStream给包装一下,然后就可以使用yield来异步获取文件内容了,这个函数我帮你包装好了,拿去就能用。