Home  >  Q&A  >  body text

javascript - How to read files in koa

Beginner to koa, using ctx in app.use to directly return the html string can be displayed, but when using fs.readFile and assigning data to ctx.body in the callback, not found is displayed on the browser. What should I do? How to write it, I couldn’t find

習慣沉默習慣沉默2732 days ago765

reply all(2)I'll reply

  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-05-16 13:38:38

    ReadFile directly is asynchronous, right? Use readFileSync?

    Or refer to this?

    var app = require('koa')();
    var fs = require('fs');
    app.use(function *(){
        this.body = yield new Promise(function(reso,reje){
                    fs.readFile(__dirname+'/app.html',function(err,data){
                        if(err) 
                            reso('error');
                        else
                         reso(data.toString());
                    })
                }).then(function(data){
                    return data
                });
    })
    
    app.listen(8910);

    reply
    0
  • 漂亮男人

    漂亮男人2017-05-16 13:38:38

    koa-sendfile

    koa 好像没有直接类似 expressres.sendFile() Such syntax requires adding middleware

    reply
    0
  • Cancelreply