http.createServer (req,res)->
res.write 'hello'
theFile=fs.createReadStream('./file.txt')
theFile.on 'end',->res.end('world')
theFile.pipe res
.listen 3001
以下是我重写的:
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来异步获取文件内容了,这个函数我帮你包装好了,拿去就能用。