码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2016-06-14 10:16:50      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

新建一个名为“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

 

技术分享

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

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

技术分享

 

代码说明:

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

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

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

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

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

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

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

第12行打印日志。

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

标签:

原文地址:http://www.cnblogs.com/teafree/p/5571554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!