Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a stream with server for nodejs (serverjs.io)

Using https://serverjs.io/documentation/reply/

I can't figure out how best to return streams? The ctx.res is a writable stream? I would like to take full advantage of the stream (transform and not read all into memory)...sockets?

I can't find any documentation. Plenty about returning streams but not with this. I'd like to use server.js because in all other respects it seems pretty decent.

like image 964
Niall Farrington Avatar asked Jun 10 '26 17:06

Niall Farrington


1 Answers

creator of server.js here. Sorry for taking so long to answer I didn't find this question before. Though I think I've read it somewhere else before?

But let's get to it, it was quite more counter-intuitive than what I expected, but not impossible. You have the code example here now:

const server = require('server');
const fs = require('fs');
const path = require('path');

const img = path.resolve('../../test/logo.png');
const stream = (read, write) => new Promise((resolve, reject) => {
  read.pipe(write).on('error', reject).on('end', resolve);
});

server(ctx => {
  return stream(fs.createReadStream(img), ctx.res);
});

Server will not work nicely with streams, but it will work perfectly with Promises so we wrap it all in a promise that will be resolved when the streaming ends.

Why/how are you using this? If you open an issue with a common case I'll probably add this as a new reply type since it seems fairly easy to add and test, while still within the scope of the library.

To answer your sub-question, ctx.res is literally express' res, but the problem is that you have to return something. That is why I'm wrapping it around a promise that will resolve only when it's finished streaming.

like image 125
Francisco Presencia Avatar answered Jun 12 '26 05:06

Francisco Presencia