Node.js 基础介绍(一)

Node.js 学习笔记一)

 

简单介绍——名称

Node.js,平时听到有好几种叫法,node Node.jsnodejs ,但是比较正式的称呼还是“Node.js”,由于它是基于Google v8JavaScriptJS)运行环境,所以一般就称之为“Node.js”。【GoogleV8引擎——对js进行解释的解释器,在Node.js中对这个解释器进行封装】

 

Node.js 具体是什么?

个人理解的Node.js呢,它就是一个服务器端的JavaScript解释器。是一个基于Google v8 JS运行环境,也可以说是供前端使用的后台语言;

怎么这么说呢,因为现在的前后端的差异越来越小了,作为前端人员,也需要了解一些后台的东西,这里的Node.js就是我们要学习的一门利用后台语言C++开发的一种基于Google v8的服务器端JS

但是,虽说Node.js是用后端语言开发的,但是我们操作它并不用说还需要去学习另一门语言,操作的是它已经封装好的东西,Node.js它采用的是还ECMA的核心语法,所有ECMA定义的知识都可以在node.js使用;但Bom dom 不能在node.js使用;

 

Node.js是函数式编程;

Node.js 最牛逼的地方 ,其实就在于它对http服务器的封装

1、Nodejs

优点:轻量(因为是模块化开发)、高效

特点:

1、模块化

2、事件驱动【这里可以看成是onRequest”事件】

3、IO异步操作(非阻塞

可以简单的看一个实例:

1、不能使用的端口号: 

  MySQL 3306

  默认端口号:80

  Tomcat默认端口号:8080

2、数据走向

"use strict"
//1、引用模块

//注意常量初始化后就不可更改
const myhttp = require('http');//请求node.js自带的HTTP模块

const myfs = require("fs");//请求文件操作模块


//2、用createServer创建服务器
//回调函数的参数:1、请求对象  2、响应对象

//回调函数,调用http模块提供的函数createServer,这个函数会返回一个对象,这个对象有一个listen方法,这个方法有一个数值参数,用于指定这个http服务器监听的端口号
 const myServer = myhttp.createServer(function (req, res) {

  //req.url:返回请求的地址即用户在端口号后面输入的地址
     console.log(req.url);
      console.log("客户端请求来了");//在客户端浏览器访问时执行创建服务器函数

req.url = req.url=="/"?"/index.html":req.url;
    //这里的path 前面会自动加上你的当前的working directory,比如这里是:D:\node\node1
     let path = "public" + req.url;  //这里就变成了D:\node\node1\public\
     let arr = req.url.split(".");
     let str = arr[arr.length-1];//判断文件后缀名
     if(str=="html"){

  //readfile 读取文件 的3个参数:
     //1、文件的位置   2、文件编码  3、文件回调函数(err:错误信息  data:文件的内容)
         myfs.readFile(path,"utf-8",function(err,data){ 

//200,表示页面的状态码:响应成功;这句还可以解决乱码问题

//状态码:
// 404 :未找到资源
//302:缓存资源
//50x:服务器出错

//res.writeHeader(200, {"Content-Type": "text/plain;charset=utf-8"});

 // res.write("<h1>hello world</h1>");      //这里的h1不会被解释,因为text/plain,如果要以HTML标签来解释,变成text/html,下面有相关例子;
             res.writeHeader(200, {"Content-Type": "text/html;charset=utf-8"});   

            res.write(data);             

   res.end();//必须写响应结束,否则会一直响应下去
         });
     }else if(str=="js"){
         myfs.readFile(path,"utf-8",function(err,data){
             res.writeHeader(200, {"Content-Type": "text/javascript;charset=utf-8"});             res.write(data);

             res.end();         });
     }else if(str=="css"){
         myfs.readFile(path,"utf-8",function(err,data){
             res.writeHeader(200, {"Content-Type": "text/css;charset=utf-8"});             

   res.write(data); 

            res.end();

         });
     }else if(str=="jpg" || str=="png"){
         myfs.readFile(path,function(err,data){
             res.writeHeader(200, {"Content-Type": "image/"+str+";charset=utf-8"});                

    res.write(data);
             res.end();

         });
     }else if(str=="woff" || str=="ttf"){
         myfs.readFile(path,function(err,data){
             res.writeHeader(200, {"Content-Type": "font/"+str+";charset=utf-8"});                

    res.write(data);

           res.end(); 

        });
     }    
});
 //3、添加端口
myServer.listen(8888);
console.log("服务启动");

【程序说明:这个程序还可以封装一下,这个只是初版,还可以优化】

简单的优化后:

app2.js

 

"use strict" //使用严格模式
//引入模块
const myhttp = require("http");
const  myfs = require("fs");
const myurl = require("url");
const fileR2 = require("./routes/fileRouter2.js");//这里一定要写到根目录去
//创建服务器,并监听
myhttp.createServer(function (req,res) {
    fileR2.sendpage(req,res);
}).listen(8989);

 

 fileRouter2.js 

"use strict"
const fileC2 = require("../controller/fileControl2.js");
exports.sendpage = (req,res)=>{
    fileC2.sendfile(req,res);
}

 fileControl2.js

"use strict"
//引入模块
const  myfs = require("fs");
const myurl = require("url");
exports.sendfile = (req,res)=> {
    "use strict"
    req.url = req.url=="/"?"/index.html":req.url;
    let pname = myurl.parse(req.url).pathname; //获取纯文件的路径名【去掉文件名的多余部分】
    let path = "public"+"\\page2"+pname; // 取路径
    let arr = pname.split(".");//获取后缀名
    let ext = arr[arr.length-1];
    if(ext=="html" || ext=="htm"){
        myfs.readFile(path,"utf-8",function(err,data) {//读取文件并且创建回调函数
            res.writeHead(200,{"Content-Type" : "text/html;charset=utf-8"});
            res.write(data);
            res.end();
        });
    }else if(ext=="css"){
        myfs.readFile(path,"utf-8",function(err,data) {//读取文件并且创建回调函数
            res.writeHead(200,{"Content-Type" : "text/css;charset=utf-8"});
            res.write(data);
            res.end();
        });
    }else if(ext=="js"){
        myfs.readFile(path,"utf-8",function(err,data) {//读取文件并且创建回调函数
            res.writeHead(200,{"Content-Type" : "text/javascript;charset=utf-8"});
            res.write(data);
            res.end();
        });
    }else if(ext=="png" || ext=="jpg" || ext=="gif"){
        myfs.readFile(path,function(err,data) {//读取文件并且创建回调函数
            res.writeHead(200,{"Content-Type" : "image"+ext+";charset=utf-8"});
            res.write(data);
            res.end();
        });
    }else if(ext=="woff2" || ext=="ttf"){
        myfs.readFile(path,"utf-8",function(err,data) {//读取文件并且创建回调函数
            res.writeHead(200,{"Content-Type" : "font"+ext+";charset=utf-8"});
            res.write(data);
            res.end();
        });
    }
};

  

这样主程序App2.js 看起来就精简吧,相互之间的结构也更加清晰了

 

 

 

3、路由

【特别注意】nodejs的每一个文件都是私有的;

要设置为一个公开的接口才可以访问,可以用exports 或者module.exports设置公开接口:

exports.暴露出去的方法名=自己内部的方法名/直接写方法 

 【加上一个nodejs比较简单的:箭头函数】

普通函数:

Function func1 ( x,y ) {

函数体

}

等价于箭头函数

x,y=>{

函数体

}

nodejs 新人,欢迎指正

posted @ 2017-10-19 20:28  横竖撇捺_ser  阅读(219)  评论(0编辑  收藏  举报