一 、 helloworld实例
上一章中介绍了 搭建node开发环境, 本节主要介绍初步的开发使用。首先选择一个开发工具,我个人喜欢使用Sublime Text2 ,使用简单方便。下载地址:http://www.sublimetext.com/ 或者百度直接可以搜索到。
首先在d盘下建立nodetest文件夹,将文件夹拖放到sublime编辑器中:
左侧会列出工程文件,简单吧,现在创建一个文件helloworld.js 加入下面代码:
var http = require("http"); //引入http库
//创建server监听
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
console.log("Server has started")
保存文件。
运行文件,打开cmd控制台,进入d盘下建立nodetest文件夹下,运行 node helloworld.js :
好了,服务器启动了,现在通过ie浏览器打开 http://localhost:8888/
会发现服务器返回信息 Hello World ,该数据是由response.write("Hello World"); 目前知道就可以了。
二 、 下面我们来看一下服务器代码是如何操作的。
上面的服务器代码我们来进行分布解析,
首先 , http.createServer(function_a).listen(8888);
function_a是我们提炼出来的函数,内容为:
function function_a(request , response){
............内容
}
也就是说,function_a函数作为参数,存在于http.createServer()中. 将以上代码修改后,
var http = require("http");
function onRequest(request , respone){
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);