Nodejs及ES6简单入门

Node.js

在这里插入图片描述



简介

简单来讲,Node.js就是能在服务端运行的JavaScript(以前服务端开发以java居多,前端人员等着服务端准备好交互浪费时间)—主要是方便前端人员

网上有段话关于tomcat的说法很形象(跑题ing)
我家有一台机器,可以把石头变成金子。你寄给我一箱石头,让我把它们变成一箱子金子再快递回给你。这个机器就是一个web项目。石头是请求,金子是响应,我家等同于一个服务器。
现在你把石头寄过来了,机器可不会自己接受石头并且把它加工成金子再还给你。至此,我派上用场了。我接受石头,把它给机器,变成金子后再打包快递给你。我就是tomcat。没有我,你的一箱子石头邮过来也没用。我家机器不会搭理你,更不会给你金子。


web服务器
//引入node.js内置http模块
var http = require("http");

function service(request,response){
    //发送http头部
    response.writeHead(200,{"Content-Type":"text/plain"});
    //发送响应数据(write和end都能向前端返回数据,end方法结束请求,如果没有end前端会一直处于等待状态)***
    response.write("hello world\n");
    response.end("hello world \n");
}
//基于service函数创建server服务器
var server = http.createServer(service);
//server服务器监听于8088端口
server.listen(8088);
console.log("服务器运行在http://127.0.0.1:8088");

//访问地址http://127.0.0.1:8088/即可看到hello world
获取参数
//引入node.js内置http模块
var http = require("http");
var url = require("url");

function service(request,response){
    response.writeHead(200,{"Content-Type":"text/plain"});
    //解析请求地址
    var params = url.parse(request.url,true).query;
    for (var key in params) {
        response.write(key +" = "+params[key]);
    }
    response.end("");
}

//基于service函数创建server服务器
var server = http.createServer(service);
//server服务器监听于8088端口
server.listen(8088);
console.log("服务器运行在http://127.0.0.1:8088?id=123&name=lxw");

模块系统

简单来说,别人写的js就是一个模块,我们在可以引用别人写的js文件

/*xw.js*/
//service函数和之前一样
function service(request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello Node.js');
}
//加一个hello函数  在控制台打印
function Hello(){
    console.log('hello from xw.js');
}
/*
这两个函数是不能直接外部调用的!
我们得通过exports 指定如何调用他们
1.允许外部通过 hi() 这个函数名称调用 sayHello() 
2.允许外部通过 service() 函数名称调用service()
*/
exports.hi = sayHello;
exports.service = service;

/*node.js*/
//引入http和xw模块
var http = require('http');
var xw = require('./xw');
xw.hi();
//基于xw.service()创建server服务器
var server = http.createServer(xw.service);
server.listen(8088);

/效果和前面一致,但是我们可以看到控制台多出一句hello from xw.js

路由

requestHandlers.js

function listCategory() { 
    return "a lot of categorys";
}    
function listProduct() { 
    return "a lot of products";
} 
exports.listCategory = listCategory; 
exports.listProduct = listProduct; 

router.js

function route(handle, pathname) { 
  if (typeof handle[pathname] === 'function') { 
    return handle[pathname](); 
  } else {
    return pathname + ' is not defined';
  } 
} 
exports.route = route;

server.js

var http = require("http"); 
var url = require("url"); 
   
function start(route, handle) { 
  function onRequest(request, response) { 
    var pathname = url.parse(request.url).pathname; 
    var html = route(handle, pathname); 
    response.writeHead(200, {"Content-Type": "text/plain"}); 
    response.write(html); 
    response.end(); 
  } 
  http.createServer(onRequest).listen(8088); 
} 
exports.start = start;

index.js(入口模块)

var server = require("./server"); 
var router = require("./router"); 
var requestHandlers = require("./requestHandlers"); 
 
var handle = {} 
handle["/listCategory"] = requestHandlers.listCategory; 
handle["/listProduct"] = requestHandlers.listProduct; 
   
server.start(router.route, handle);
小结
  • index.js调用sever.start函数,传递handle数组以及router.js作为参数
  • 通过8088端口启动服务,onRequest处理业务
  • router.js中通过pathname为下标获得调用的真正的业务函数
  • 虽然看起来麻烦,但是如果要开发新的功能,比如listUser 只需要增添listUser函数,在index.js进行映射进handle数组就好

包资源管理器NPM

npm是node包管理分发的工具,可以方便地下载别人的js库(也可以简单理解为前端的maven)

cnpm

npm是从国外服务器下载别人的模块。cnpm 复制国外的库到国内的服务器上(用的时候cnpm install就行)

npm install -g cnpm --registry=https://registry.npm.taobao.org(网站是npm官网 -g是全局安装)
//或者更换镜像源
npm install nrm -g
nrm ls
nrm use taobao

Webpack

Webpack是前端资源打包工具,可以将多个静态资源css、js等打包成一个js文件。

npm install webpack -g
npm install webpack-cli -g
webpack -v
var path = require("path");

module.exports = {
    //入口文件
    entry: "./src/main.js",
    output: {
        //路径
        path: path.resolve(__dirname,"./dist"),
        filename: "bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ["style-loader","css-loader"]
            }
        ]
    }
}
  1. webpack可以将多个js打包成一个js
  2. webpack打包css需要安装转换的组件,并修改配置文件

ES6

简介:ECAMScript是JavaScript的标准,JS是ES的实现

let和const

var的缺点:

1.可以重复声明

2.没有常量的概念,可以随意修改

3.不支持块级作用域,属于函数级作用域

ES6引入了const 和let

  • const和let 都不能重复声明
  • let和const都支持块级作用域(比如在if语句中定义的let a,const b变量,出了代码块的作用域就不能使用了)
  • 顶层对象,在浏览器环境指的是window对象,在Node中指global`对象。ES5中,顶层对象的属性与全局变量是等价的。ES6为了改变这一点,规定var和function声明的全局变量依旧是顶层对象的属性;除此之外,规定let、const、class命令声明的全局变量,不属于顶层对象的属性
var a = 1;
window.a // 1
let b = 1;
window.b // undefined
解构赋值
//ES5
var arr = [1, 2, 3];
var a = arr[0];
var b = arr[1];
var c = arr[2];
console.log(a, b, c);
//ES6
var [a, b, c] = [1, 2, 3];
console.log(a, b, c);
箭头函数
//JS中经常要用到回调函数,而一般回调又以匿名函数的形式出现,每次写function就比较繁琐。箭头函数看起来更加优雅简洁.
var add = function(a,b){
    return a+b;
}
var add2 = (a,b) => a+b;
函数参数
//收集剩余参数
let fn = (a, b, ...args) => {
    console.log(a);     //1
    console.log(args);  //[3, 4, 5]
}
fn(1, 2, 3, 4, 5);
//形参可以直接赋值(如果没传入实参就用形参)
let fn = (a, b=2, c=3) => {
    console.log(a, b, c);   //1, 5, 3
}
fn(1, 5);
数组
//map(接收一个函数,将原数组中所有元素通过这个函数处理并放入新数组返回)
let arr = ['1','2','3','4','5'];
console.log(arr);
arr = arr.map(s => parseInt(s));
console.log(arr);

//reduce(从左到右依次把数组中的元素用函数处理。第一个参数是函数,如果有第二个参数---就是一个初始值)
let arr = ['1','2','3','4','5'];
temp = arr.reduce((a,b) => a*b);
console.log(temp)	//120
temp = arr.reduce((a,b) => a*b,10);
console.log(temp)	//1200

//filter(根据条件判断,去掉不想要的数据,返回想保留的数据)
let arr = [1, 2, 3, 4, 5, 6];
//直接通过布尔值判断,为true的保留,为false的去掉
let result = arr.filter(item => item%2 == 0);  //保留可以被2整除的数
console.log(result);    //[2,4,6]

//forEach(第一个参数是数组的值,第二个参数是数组的下标)
let arr = [10, 20, 30, 40,50];
arr.forEach((item, index) => console.log(index + ":" + item));    //0:10 1:20 2:30 3:40 4:50);
字符串
//ES6新增了2个字符串方法:startsWith、endsWith
//引入了字符串模板,解决了ES5字符串拼接的问题
var title = "标题";
var content = "内容";
var str =  "<div>\
<h2>title:"+title+"</h2>\
<p>content:"+content+"</p>\
</div>";
console.log(str);
str = `<div>
    <h2>title:${title}</h2>
    <p>content:${content}</p>
</div>`;
console.log(str);
面向对象
/*ES5 构造函数伪装成类来使用*/
function Person(name, age){     
    this.name = name;
    this.age = age;
}
/*函数需用原型prototype来添加,不便于维护*/
Person.prototype.getName = function (){
    console.log(this.name);
}
Person.prototype.getAge = function (){
    console.log(this.age);
}
var person = new Person('lxw', 20);
person.getName();  //lxw
person.getAge();   //20

/*ES6引入了class关键字,方便管理维护*/
class Person{ 
    //构造器
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
    getName(){
        console.log(this.name);
    }
    getAge(){
        console.log(this.age);
    }
}
var person = new Person('lxw', 20);
person.getName();
person.getAge();

/*es5的继承*/
function Student(name, age, grade){
    Person.call(this, name, age); //通过call来继承父类
    this.grade = grade;
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.getGrade = function (){
    console.log(this.grade);
}
var student = new Student('lxw', 20, 88);
student.getName();      //lxw
student.getAge();       //20
student.getGrade();    //88

/*ES6的继承可以类比java*/
class Student extends Person{ 
    constructor(name, age, grade){
        super(name, age);   //等同于call继承父类
        this.grade = grade       
    }
    getGrade(){    
        console.log(this.grade);
    }
}
var student = new Student('lxw', 20, 88);
student.getAge();
JSON
let json1 = {"name":"lxw", "age":20};
let str = JSON.stringify(json1);  //json转字符串
console.log(str);
let json2 = JSON.parse(str); //字符串转json
console.log(json2);
console.log(typeof json2)  //object
promise
//promise是一个对象,可以保留事件执行的结果(应用于异步操作时指定操作成功与失败的结果)
const promise = new Promise(function (resolve, reject) {
   setTimeout(() => {
       let num = Math.random();
       if(num < 0.5){
           resolve("成功,当前的num:"+num);
       } else {
           reject("失败,当前的num:"+num);
       }
   },1000);
});
promise.then(function (msg) {
    console.log(msg);
}).catch(function (msg) {
    console.log(msg);
});
console.log("1秒后出现结果");
对象和数组的一些方法
//对象
let person ={name:"lxw",age:20}
Object.keys(person)//获取键
Object.values(person)//获取值
Object.entries(person)//获取键值对
Object.assign(person,{address:"China"}) //拷贝对象属性到person中
//数组
let arr = [7,12,3,5];
arr.find(i => i%2===0); //参数是一个函数 查找满足条件的第一个元素
arr.findIndex(i => i===3); //参数是一个函数 找到满足条件的第一个元素下标位置
arr.includes(3); //返回布尔值

一星陨落,黯淡不了星空灿烂;一花凋落,荒芜不了整个春天。人生并非只有一处缤纷烂漫,那凋零的是花,不是春天。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值