2. nodejs 基础学习

来源:互联网 发布:淘宝卖家推广平台 编辑:程序博客网 时间:2024/05/16 17:07

注意: 本文档的书写源自何老师 在51cto上的讲解。

部分代码来源:http://www.yuankuwang.com 

何老师视频:http://edu.51cto.com/course/course_id-7066.html  (for free)


前提是,我们已经保证了nodejs的环境已经完成

1 在屏幕上打印hello world

  (1)  touch hello.js

        (2)  echo “console.log('hello world‘)” > hello.js

          (3)  node hello.js

                when you finish step 3, you will find the hello world in the terminal.

2.  如何实现简单的网页访问(http)

        (1)touch  http.js

          (2).w  var  http  =  require('http');
                http.createServer(function  (request,  response)  {
                  response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});
    if(request.url!=="/favicon.ico"){  //清除第2此访问  
        console.log('访问');
        response.write('hello,world');
        response.end('hell,世界');//不写则没有http协议尾,  在浏览器端会出现转圈,但写了会产生两次访问  
    }
 }).listen(8000)

 console.log('Server  running  at  http://127.0.0.1:8000/'); 

3.   函数

      普通函数:在调用的同一个文件下,可以直接调用

//---普通函数      
function  fun1(res){      
    res.write("你好,我是fun1");      
}

       非普通函数:不在同一个文件下

   (1)mkdir models ; touch function.js

                  (2)  //在一个文件中,只包含一个函数

  function  controller(req,res){      
        call('hello',req,res);      
    res.end("");      
}      

function  call(res){      
    console.log('call');      
}      
module.exports  =  controller;   

//包含多个函数

var otherfun = require('./models/function.js');

module.exports={      

  getVisit:function(){      
    return  visitnum++;      
    },      
    add:function(a,b){      
    return  a+b;      
    }      
}






       

  

0 0
原创粉丝点击