Say hello to node.js

node.js API 查询:http://nodejs.org/docs/v0.6.13/api/

 1 //*************node.js-v0.6.13****************//
2
3 ///////////////////////////////////////////////
4 // say hello in console
5 var sys=require("util");
6 sys.puts("Hello World!"); // console.log("Hello World!");
7
8 ///////////////////////////////////////////////
9 // say hello in web server, retun as text/html
10 var sys=require("util"),
11 http=require("http");
12
13 http.createServer(function(request, response)
14 {
15 response.setHeader("Content-Type", "text/html");
16 // set the statusCode before "response.write" method.
17 response.statusCode = 200;
18 response.write("Hello World!");
19 response.end();
20 }).listen(8080);
21
22 // write log to console
23 sys.puts("Server running at http://localhost:8080/");
24
25 ///////////////////////////////////////////////
26 // say hello in web server,retun as text/plain
27 var http=require('http');
28
29 http.createServer(function(request,response){
30 response.writeHead(200,{'Content-Type':'text/plain'});
31 response.end('Hello World\n');
32 }).listen(8088);
33
34 // write log to console
35 console.log('Server running at http://127.0.0.1:8124/');
36
37 ///////////////////////////////////////////////
38 // write strings to buffer and print them in utf-8(ascii/utf8/binary)
39 var Buffer =require("buffer").Buffer,
40 buf=new Buffer(256),
41 len=buf.write('\u00bd+\u00bc=\u00be',0);
42
43 // write log to console
44 console.log(len+" bytes: "+buf.toString('utf8',0,len));
45
46 ///////////////////////////////////////////////

代码解析:

1.require()导入模块,把 require() 方法的返回值赋值给一个变量,在 JavaScript 代码中直接使用此变量即可 。

2.http.createServer 是http模块的方法,作用是创建并返回一个新的web server对象。给服务绑定一个回调,用以处理请求。

3.通过 http.listen() 方法就可以让该 HTTP 服务器在特定端口监听。



posted on 2012-03-20 17:09  Bruce Lai  阅读(245)  评论(0编辑  收藏  举报