Search code examples
node.jspipepartialhttpserver

Send a huge content range using streams


How to send a part of file using read stream in response on HTTP request?

I want to send an arbitrary Content-Range of a huge file.

I can't use events when I do fs.createReadStream('hugeFile.bin').pipe(response) to filter out a part of readable stream. I can create a fake writable stream, which omits (like > /dev/null) a part of data, but chunk size may be not a multiple of a first part to send.

How to solve the problem?


Solution

  • Take a look at https://nodejs.org/dist/latest-v6.x/docs/api/fs.html#fs_fs_createreadstream_path_options.

    In particular, the start and end options - these let you set the byte offsets in the file to start and stop reading from.

    So basically you'd do:

    fs.createReadStream('hugeFile.bin', { start: firstByte, end: lastByte }).pipe(response)
    

    or the moral equivalent and it'd do what you want.