node.js入门(二) 第一个程序 Hello World

新建一个名为“hello.js”文本文件,然后输入如下内容

 

 1 //载入http模块
 2 var http = require('http');
 3 //构建一个http服务器
 4 var server = http.createServer(function(request,response){
 5     response.writeHead(200,{'Content-Type':'text/plain'});
 6     response.write('Hello World!');
 7     response.end();
 8 });
 9 //启动http服务器,并开始侦听3000端口号
10 server.listen(3000);
11 //在控制台打印日志 
12 console.log('Server running at http://127.0.0.1:3000');

在命令行窗口中“cd”到当前目录,然后执行如下命令

node hello.js

 

image

如果在控制台能打印出“Server running at http://127.0.0.1:3000”,说明我们的第一程序已经运行正常。

然后打开浏览器,在地址栏输入

image

 

代码说明:

在浏览器中我们将看到“Hello World!”。

第2行先载入http模块,我们创建http服务器时需要这个模块,

第4行就是创建了一个http服务器,

第5行在HTTP响应中写入http头,

第6行写入http体,也就是我们在浏览器中看到的内容,

第7行是结束http响应,返回浏览器,

第10行启动服务并侦听3000端口,

第12行打印日志。

posted @ 2016-06-14 09:36  teafree  阅读(203)  评论(0编辑  收藏  举报