Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do content encoding properly in node.js?

Given the following code

var http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text'});
    response.write("Okay – so recently I’ve started presenting a session to various groups involving the well known IOC container “StructureMap”", 'utf8');
    response.end();
}).listen(8080);

I get the output

Okay – so recently I’ve started presenting a session to various groups involving the well known IOC container “StructureMap†– and despite being pretty clear about the contents of said talk I’m getting quite a bit of backlash for demonstrating anything that even remotely resembles service location.

This is clearly wrong - but is it wrong because I've got the wrong encoding (UTF8 should do it... right?... right?) or is it wrong because node is doing something weird?

I am using the latest version of node, cloned from github master yesterday.

like image 434
Rob Ashton Avatar asked Mar 05 '11 18:03

Rob Ashton


1 Answers

If you want it to be downloaded as a text file with the proper encoding, you should use the text/plain; charset=utf-8content type. Simply using text isn't enough. I just tested it and it works as expected. Change plain to html to make the browser use its default styles on the text.

like image 127
Carter Allen Avatar answered Nov 01 '22 12:11

Carter Allen