1

Say I have this:

const writeResponse = function(file: string, s: Socket){

   s.write([
    'HTTP/1.1 200 OK',
    'Content-Type: text/javascript; charset=UTF-8',
    'Content-Encoding: UTF-8',
    'Accept-Ranges: bytes',
    'Connection: keep-alive',
   ].join('\n') + '\n\n');

  getStream(file)
    .once('error', function (e: any) {
      s.end('error: ' + e && e.stack || e.message || util.inspect(e));
    })
    .pipe(s)
    .once('error', function (e: any) {
      s.end('error: ' + e && e.stack || e.message || util.inspect(e));
    });

}

the problem that I cannot figure out how to solve - if there is an error reading the file, how can I send this header instead of the success header:

HTTP/1.1 500 Cannot read file

the problem is that as far as I know, writing the file to the response has to come after writing the headers, but what if there is an error reading the file?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

1

There are two possibilities:

  • either the app holds onto the headers until errors can't happen (the entire file was buffered, for example). In that case the app will be able to send a 5xx error.
  • if the app sends a 200 header, the only possible way to signal an error to the other end is to send a truncated response. That's only possible with chunked transfer-encoding: or with content-length:. With connection:close it's impossible to tell there's been an error at the HTTP level.
Frederik Deweerdt
  • 4,943
  • 2
  • 29
  • 31