Aug 25, 2012 - node.js    1 Comment

Node.js Hello World

昨天node.js算是装好了,从今天开始要开始重拾node.js了。

当然,第一步还是 hello world, 照着官网的例子弄一个:

var http = require('http');
http.createServer(function(req, res) {
	res.writeHead(200, {
		'Content-Type': 'text/plain'
	});
	res.end('Hello World!');
}).listen(1216, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1216/');

去终端里运行一下,

$ cd ~/node
$ node helloworld.js

再到浏览器里访问一下, http://127.0.0.1:1216/

hello world 出来了。

但firebug还是给了一段警告:

The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature.

没什么好说的,这是很多老外都会忽视的编码问题。

修改代码,添加utf8声明:

var http = require('http');
http.createServer(function(req, res) {
	res.writeHead(200, {
		'Content-Type': 'text/plain;charset=UTF-8'
	});
	res.end('Hello World!');
}).listen(1216, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1216/');

重启helloworld.js, 再刷新浏览器,警告消失了。

1 Comment

  • I was having the exact same problem, and was confused, I thought the encoding had to be written at response.end(), but that is something else.

    Thank you very much!

Got anything to say? Go ahead and leave a comment!