Nodejs 学习一 NodeJs helloworld 简单封装

一 、 helloworld实例

    上一章中介绍了 搭建node开发环境, 本节主要介绍初步的开发使用。首先选择一个开发工具,我个人喜欢使用Sublime Text2 ,使用简单方便。下载地址:http://www.sublimetext.com/ 或者百度直接可以搜索到。

    首先在d盘下建立nodetest文件夹,将文件夹拖放到sublime编辑器中:1.png

左侧会列出工程文件,简单吧,现在创建一个文件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  :

2.png 好了,服务器启动了,现在通过ie浏览器打开 http://localhost:8888/ 2.png

会发现服务器返回信息 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);  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值