node自学之路(1)

1.首先安装nodejs。各种环境安装方法搜一下一大片。

一,’使用nodejs搭建第一个web服务器

  新建app.js文件,代码如下。

ar http = require('http'), //服务创建

http.createServer(function (req,res) {
    req.setEncoding("utf8");
    res.writeHead(200,{'Content-Type':'text/html'});
    res.end('Hello World!')
}).listen(3000,'127.0.0.2');
console.log('Server run at http://127.0.0.2:3000');
//这种起服务器的方法很多,但是 listen方法都没有第二个参数,这里第二个参数就是服务器的ip地址,自己可以更改为其他的ip地址

  运行 node app.js。即可启动本地HTTP服务器。打开浏览器输入地址:http://127.0.0.2:300即可看到Hello World!字符串。

代码说明:

  require('http') : 获取Node.js 原生模板提供的HTTP模板对象。

  res.writeHead : 通过res的http响应对象,编写HTTP响应的头信息,Content-Type指定返回的数据类型为文本text。也可以是其他格式。

  http.createServer() : 使用http对象API方法createServerlai创建服务器。

  listen :http对象的一个方法。其主要是启动服务器监听的端口和ip,第二个参数为可选参数,默认为本地127.0.0.1。

二,理解回调函数与异步逻辑。

  创建 calback.js文件。

  回调逻辑。

function waitFive(name,functionName) {
    var pus = 0;
    var currentDate = new Date();
    while (pus<5000){
        var now = new Date();
        pus = now - currentDate;
    }
    functionName(name);
}
function echo(name) {
    console.log(name)
};
waitFive('小明',echo);
console.log('its over');

执行结果:

  异步逻辑

function waitFive(name,functionName) {
    setTimeout(function () {
        functionName(name);
    });

}
function echo(name) {
    console.log(name)
};
waitFive('小明',echo);
console.log('its over');

执行结果

代码说明:

  1.理解while语句。先判断条件是否正确,正确后执行代码块。然后再判断条件是否正确,正确再次执行代码块。不断循环。如过判断条件为(true)则永远执行下去。

  2.这是js的回调逻辑,区别异步逻辑。

  3.setTimeout()函数是一个异步函数。

原文地址:https://www.cnblogs.com/iwang5566/p/nodejs.html