node.js应用程序由如下三部分组成
1>导入所需模块:使用require指令来加载node.js模块
2>创建服务器:服务器可以监听客户端请求,类似于apache、nginx等
3>接收请求与响应请求:接收客户端/浏览器发送过来的请求,将处理得到的数据返回
如下是第一个例子
1//步骤1:导入所需模块 2//这里我们使用require指令来载入http模块,并将实例化的HTPP赋值给变量http 3var http = require('http'); 4 5//步骤2:创建服务器 6//这里我们使用http.createServer()创建服务器 7//并使用listen方法绑定3000端口 8//通过request、response参数来接收和响应数据 9http.createServer(function(request, response) { 10 11 //响应状态:200;内容类型:text/html 12 response.writeHead(200 , {"Content-Type":"text/html"}); 13 //响应内容 14 response.write("<h1>Node.js</h1>"); 15 //响应结束 16 response.end("<p>Hello World</p>"); 17 //端口号:3000 18}).listen(3000); 19//控制台打印出信息 20console.log("HTTP server is listening at port 3000.");
控制台消息

浏览器请求如下
