javascript - 如何用 node.js 的 koajs 模块重写如下代码?
大家讲道理
大家讲道理 2017-04-10 14:38:36
[JavaScript讨论组]
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。

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(1)
PHP中文网

很简单,先把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);
      }
    }
  }
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号