Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode HTTP response body as UTF-8 in node.js

This is currently my entire node.js server code:

require('http').createServer(function (req, resp) {
    var html = [
        '<!DOCTYPE html>',
        '<html>',
            '<head>',
                '<meta charset="utf-8" />',
                '<title>Sample Response</title>',
            '</head>',
            '<body>',
                '<p>Hello world</p>',
            '</body>',
        '</html>'
    ].join('');

    resp.writeHead(200, {
        'Content-Length': Buffer.byteLength(html, 'utf8'),
        'Content-Type': 'application/xhtml+xml;'
    });
    resp.write(html, 'utf8');
    resp.end();
}).listen(80);

Based on my understanding of the node.js documentation, the second 'utf8' argument to resp.write() should cause node to encode the html string as UTF-8, not the UTF-16 that JavaScript strings are natively represented as. However, when I point my browser to localhost:80, view the source, and save it to a local html file, Notepad++ tells me the file is encoded in UTF-16. Furthermore when I run it through the W3C html validator tool it also complains about "Internal encoding declaration utf-8 disagrees with the actual encoding of the document (utf-16)".

How do I force node.js to encode my HTTP response body as UTF 8?

like image 842
Drake Avatar asked Oct 12 '13 20:10

Drake


Video Answer


1 Answers

maybe you have to do:

'Content-Type': 'application/xhtml+xml; charset=utf-8'
like image 154
Jonathan Ong Avatar answered Oct 07 '22 07:10

Jonathan Ong