V
V
Vladimir2018-02-16 13:57:44
Node.js
Vladimir, 2018-02-16 13:57:44

How to perform file transfer after 'close' event in koajs?

It is necessary to send the file to the client after the completion of all operations with it.
Here's what I'm trying to do:

js code
async create(ctx) {
    ctx.attachment(filename);
    ctx.set('Content-Type', mimetype);

    const arch = fs.createWriteStream(path.join(__dirname, 'someArchive.zip'));

    ctx.body = arch.on('close', () => {
      console.log('writeStream was closed');
      fs.createReadStream(file);
    });
  },
mistake

Error: Cannot pipe, not readable
at WriteStream.Writable.pipe (_stream_writable.js:231:22)
at respond (\node_modules\koa\lib\application.js:241:43)
at handleResponse (\node_modules\koa\lib\ application.js:148:34)
at

The method is obviously wrong, but I do not know how to do it right. This method was prompted by an example from the office. site:
stream

const PassThrough = require('stream').PassThrough;
app.use(async ctx => {
ctx.body = someHTTPStream.on('error', ctx.onerror).pipe(PassThrough());
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2018-02-19
@MegaBatz

I'll answer my own question :)

app.use(async ctx => {
  await new Promise((resolve, reject) => {
    const stream = fs.createWriteStream(...)
    stream.on('close', () => {
      ctx.body = fs.createReadStream(...)
      resolve()
    })
  })
})

This is the answer from github. In my personal implementation, I also used Promise, but not in such a visual implementation. Here is such a crutch, because koa most likely does not have an internal implementation.

T
timfcsm, 2018-02-16
@timfcsm

look towards long polling or web sockets
in your case, I think the first option is enough

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question