node.js学习笔记(一)

刚刚接触Node.js,从学习网站上跟着视频学习,也查看了一些别人学习node的笔记博客,看到一篇学习Node.js的6个步骤这边文章,借鉴了一些的东西。

第一步:打好基础:

  • JavaScript 的特性和语法。假如你对 JavaScript 还不熟悉的话,推荐书籍及链接:
  • Node.js 是什么?Node.js与JavaScript的区别是什么?
    • node.js和javascript区别还是挺大的,1个平台,1个是编程语言
    • javascript是客户端编程语言,需要浏览器的javascript解释器进行解释执行

    • node.js是一个基于Chrome JavaScript运行时建立的平台,它是对Google V8引擎进行了封装的运行环境;

    • 简单的说node.js就是把浏览器的解释器封装起来作为服务器运行平台,用类似javascript的结构语法进行编程,在node.js上运行。

  • Node.js的优点?Node.js的缺点?
    • Node.js优点:
      1、采用事件驱动、异步编程,为网络服务而设计。其实Javascript的匿名函数和闭包特性非常适合事件驱动、异步编程。而且JavaScript也简单易学,很多前端设计人员可以很快上手做后端设计。
      2、Node.js非阻塞模式的IO处理给Node.js带来在相对低系统资源耗用下的高性能与出众的负载能力,非常适合用作依赖其它IO资源的中间层服务。3、Node.js轻量高效,可以认为是数据密集型分布式部署环境下的实时应用系统的完美解决方案。Node非常适合如下情况:在响应客户端之前,您预计可能有很高的流量,但所需的服务器端逻辑和处理不一定很多。
    • Node.js缺点:
      1、可靠性低
      2、单进程,单线程,只支持单核CPU,不能充分的利用多核CPU服务器。一旦这个进程崩掉,那么整个web服务就崩掉了。
  • Node.js适用场景?Node.js不适用的场景?
  • Node.js的基本语法。Node.js的特性:
    • 单线程
    • 异步 IO
    • 事件驱动
  • npm 是什么?npm的基本使用
  • REPL

 node.js的学习笔记

1.安装和hello。

首先,去http://nodejs.cn/ 下载安装,安装很简单,下一步下一步就哦了。然后在path中配置一下安装目录即可,msi会把npm(Node Package Manager)一并装上。

这时使用cmd命令窗口 node -v ,npm -v命令查看下安装的版本.

1.1、hello,world

在node工程目录中新建一个文件hello.js,里面敲一行代码 console.log('hello,world');

在文件下按住shift加鼠标右击进入命令行控制台,进入到Node.js工程目录敲node hello.js

控制台输出了“hello, nodejs.”

1.2、web版的hello,world

在node工程目录中新建一个one-demo.js,代码如下

var http = require('http');//内置模块引用http服务
http.createServer(function(request,response){//创建服务,向服务器发送的对象,服务器想浏览器返回的对象
     response.writeHead(200,  {'Content-Type':  'text/html;  charset=utf-8'});  //服务协议头,输出类型,编码格式
    if(request.url!=="/favicon.ico"){  //清除第二次访问 
        console.log('访问');
        response.write('hello,world');//页面输出的内容
        response.end('');//不写则没有http协议尾,但写了会产生两次访问 
    } 
}).listen(8000);//监听端口
console.log('Server running at http://127.0.0.1:8000/ ')

在命令行中启动服务,敲 node one-demo.js

然后打开浏览器地址栏输入http://localhost:8000,看见页面上输出Hello World! 就成功了。

 2.函数调用

2.1本地函数

在node工程目录中新建一个two-demo.js,代码如下

var http = require('http');//必须存在
http.createServer(function(request,response){//创建服务
    response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//协议头
    if(request.url!=='/favicon.ico'){//清除第二次访问
        fun1(response);
        response.end('');//协议尾
    };
}).listen('8000');
console.log('sever running at http://127.0.0.1:8000/');
//本地函数
function fun1(res){
    console.log('fun1');
    res.write('我是fun1')
}

 命令下输出

 

 2.2其他页面函数

 在同目录下新建js文件夹,创建fun.js

/**
function fun2(req,res){
    call('hello',req,res);
    res.write('fun2')
};
module.exports = fun2;//只支持一个函数
**/
//支持多个函数
module.exports={      
    getVisit:function(res){      
        res.write('jiayou')
    },      
    add:function(a,b){  
        b.write('hello');    
        return  a+b;   

    }      
}  

隐藏的是只支持一个的函数

two-demo.js内容:

var http = require('http');//必须存在
var mode = require('./js/fun.js');//mode等于函数名
http.createServer(function(request,response){//创建服务
    response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});//协议头
    if(request.url!=='/favicon.ico'){//清除第二次访问
        // fun1(response);//本地函数
        // mode(request,response);//一个函数的
        // mode.getVisit(response);//多个函数的
        // mode.add(request,response);//多个函数的
        //----用函数名的字符串调用--
        funadd = 'add';
        mode[funadd](request,response);//等于 mode.add(request,response);等于mode['add'](request,response)
        mode['getVisit'](response);
        response.end('');//协议尾
    };
}).listen('8000');
console.log('sever running at http://127.0.0.1:8000/');
//本体函数
function fun1(res){
    console.log('fun1');
    res.write('我是fun1')
}

执行命令:

 3.调用模块,4.路由,5.读写文件,6.读图片,7.路由改造,8.异常处理;都写到一起了,以下代码是异常处理:

ten-demo.js

var http = require('http');//内置模块引用http服务
var url = require('url');//内置模块引用url服务
var router= require('./router2');//路由
var flag = require('./js/flag');//异常输出
http.createServer(function(requset,response){//创建服务,向服务器发送的对象,服务器想浏览器返回的对象
    if(requset.url!=='/favicon.ico'){//清除第二次访问
        pathname = url.parse(requset.url).pathname;//url参数
        pathname = pathname.replace(///,'');//正则转换
        console.log(pathname);
        // router[pathname](response);//路由参数
        try{//异常处理适用于同步读取
            // router[pathname](response);//对路由异常做判断
            data = flag.exc(10);
            response.write(data.toString());
             response.end('');
        }catch(err){
            console.log('aaaaa='+err);    
            response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});        
            response.write(err.toString());        
            response.end('');
        }
    }
}).listen('8000');
console.log('服务器运行网址http://127.0.0.1:8000')

route2.js

/**
    路由+图文输出
**/
var readfile = require('./js/readfile');//引用模块
function abc(res){//封装函数
    res.writeHead(200,{'Content-Type':'text/html;charset = utf-8'});//协议头
    function recall(data){
        res.write(data);
        res.end('');
    };
    return recall;
}
module.exports={//路由
    login:function(res){
        //采用闭包;
        recall = abc(res);
        readfile.readfile('./views/login.html',recall);
        
    },
    zhuce:function(res){
        recall = abc(res);
        readfile.readfileSync('./views/zhuce.html',recall);
        res.end('');
    },
    writeimg:function(res){
        res.writeHead(200,{'Content-Type':'image/jpeg'});//协议头,对于图片的输出
        readfile.readImg('./img/pig.jpg',res);
    }
    /**
        可理解为路由调用页面页面调用另一个路由
    **/
}

readfile.js

/**
    同步和异步读取,同步是一步一步执行;异步为先执行其他的,最后在执行;可同步执行
**/
var fs = require('fs');//node自带的操作对象;
module.exports={
    readfile:function(path,recall){//异步读取
        fs.readFile(path,function(err,data){
            if(err){
                console.log(err);               
            }else{
                console.log(data.toString());
                recall(data);
            };

        });
    },
    readfileSync:function(path,recall){//同步读取 path读文件的路径
        var data = fs.readFileSync(path,'utf-8');//uft-8编码读取路径赋值给data
        console.log(data);
        console.log('同步放法执行完毕')
    },
    writefile:function(path,data,recall){//异步写入
        fs.writeFile(path,data,function(err){
            if(err){
                throw err;//异步错误处理
            }
            console.log(data);
        })
    },
    writefileSync:function(path,data){//同步写入
        fs.writeFileSync(path,data);
        console.log(data);
    },
    readImg:function(path,res){//读取输出图片
        fs.readFile(path,'binary',function(err,file){
            if(err){
                console.log(err);
                return;
            }else{
                console.log(path);
                res.write(file,'binary');
                res.end('')
            };
        });
    }
}

falg.js

module.exports={
    exc:function(flag){
        if(flag==0){
            throw  '我是例外'; 
        };
        return 'success'

    }
}

因为对异常进行了绝对处理。所以成功则返回success.

原文地址:https://www.cnblogs.com/qianmojing/p/6209081.html