restify / node-restify

The future of Node.js REST development
http://restify.com
MIT License
10.71k stars 982 forks source link

Restify can't sendRaw none `utf8` data - it always encoded to utf-8 #1852

Open denhub opened 4 years ago

denhub commented 4 years ago

Hello!

Thanks for Restify - it's absolutely cool!

I found a bug in the function sendRaw - when you try to send none utf8 data in response - you can't do it. Data always will be encoded to utf-8.

I use charSet - to set latin1 encoding for sending ansi mp3-file.

res.charSet('latin1').sendRaw(200, mp3fileData,{
    'Content-Type': 'audio/mpeg',
});

But it's take affect only for Content-Type field.

Cause

In response.js does not send second param encoding to http write method. Http Docs. https://github.com/restify/node-restify/blob/9153587c023a876237c1d8bc7491fee4984d9074/lib/response.js#L874

Are you willing and able to fix this?

Yes I can.



    // Send body if it was provided
    if (res._data) {
        // https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback
        // Default: 'utf8'
        let encoding = 'utf8';

        // Check :: is encoding valid?
        // in my point of view - we must validate encoding - in charSet() method
        // https://nodejs.org/docs/latest-v12.x/api/buffer.html#buffer_buffers_and_character_encodings
        let characterEncodingsSupportedByNodeJs = [
            'utf8',
            'utf16le',
            'latin1',
            'base64',
            'hex',
            'ascii',
            'binary',
            'ucs2',
        ];
        let characterEncodingsSupportedByNodeJs_id = characterEncodingsSupportedByNodeJs.indexOf(res._charSet);
        if ( characterEncodingsSupportedByNodeJs_id > -1 ) encoding = characterEncodingsSupportedByNodeJs[characterEncodingsSupportedByNodeJs_id];

        res.write(res._data, encoding);
    }

``
denhub commented 3 years ago

Any comments? A year has passed :-)

kolbma commented 2 years ago

https://nodejs.org/api/http.html#requestwritechunk-encoding-callback

The encoding argument is optional and only applies when chunk is a string. Defaults to 'utf8'.

So why you don't use binary buffer for a binary data?