如何用 node.js 的 koajs 模块重写如下代码?
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。
node.js javascript-next JavaScript
noface
10 years, 3 months ago
Answers
很简单,先把createReadStream给包装一下,然后就可以使用yield来异步获取文件内容了,这个函数我帮你包装好了,拿去就能用。
var koa=require("koa");
app=koa()
app.use(function*(next){
this.body = 'hello'
this.body += yield createReadStream('./file.txt')
this.body += 'world'
})
app.listen(3000)
//包装一下createReadStream
function createReadStream(){
var stream=require("fs").createReadStream.apply(null, arguments);
return function*(end){
if (end) {
if (stream.end) stream.end();
else if (stream.close) stream.close();
else if (stream.destroy) stream.destroy();
return;
}
return yield read(stream);
};
function read(stream) {
stream.pause();
return function(done) {
if (!stream.readable) {
return done();
}
stream.on('data', ondata);
stream.on('error', onerror);
stream.on('end', onend);
stream.resume();
function ondata(data) {
stream.pause();
cleanup();
done(null, data);
}
function onerror(err) {
cleanup();
done(err);
}
function onend(data) {
cleanup();
done(null, data);
}
function cleanup() {
stream.removeListener('data', ondata);
stream.removeListener('error', onerror);
stream.removeListener('end', onend);
}
}
}
};
石更不起来君
answered 10 years, 3 months ago