手机版 欢迎访问it开发者社区(www.mfbz.cn)网站

当前位置: > 开发

Nodejs学习笔记

时间:2021/6/3 9:59:30|来源:|点击: 次

说明: 本笔记写于2018.12 , 所用的nodejs版本较低, 仅供学习交流

ES6介绍

  • ES6是什么
  • 有哪些新特性

ES6新特性学习

变量定义

使用let代替var, 如果是常量则使用const

解构赋值

  • 数组
  • 对象
  • 函数参数

函数特性

  • 函数参数默认值
  • lambda函数(箭头函数)

NodeJS介绍

  • 单线程
  • 异步IO

npm

  • package.json 记录了依赖的包

promise

看代码



let a = 10;

console.log(a);

var b = 10;
console.info(b);


const c = 100;
console.info(c);
//c = 1000; //error





//数组
arr = [1, 2, 3, 4];
let[a, b, c, d] = arr;
console.log(a, b, c, d);



//对象
const obj = {name:"yqq", addr:"shenzhen", age:10};
let{name, addr, age} = obj;
console.log(name, addr, age);


//函数参数
const person = {name:"yqq", age:11};
function showInfo({name, age}) {
    console.log(name, age)
}
showInfo(person);


//函数参数默认值
function show(name, addr="shenzhen") {
    console.log(name, addr)
}

show("yqq");
show("Tom");
show("Tom", "Beijing");


//lambda函数


var function1 = (age) => {
    console.info(age);
};
function1(13);


//继承

class Person{

    constructor(name) {
        this.name = name;
        console.info("Person 构造函数", name)
    }


    say(){
        console.log(`name:${this.name}`) //raw string

    }

}


class Stu extends  Person{


    say(){
        console.log(`stu name:${this.name}`) //raw string

    }

}


var person = new Person("yqq") ;
person.say();

let stu = new Stu("stu1");
stu.say();



async / await

//异步IO



let fs = require("fs");

//异步
fs.writeFile("test.txt", "this is test string." , function () {
    console.log("写完了")
});

//同步
fs.writeFileSync("test2.txt", "this is test string.", "");

console.log("执行了");
console.log("执行了");

全局变量


//console.log(global.process);
//console.log(global.process);
//console.log(global.path);
// console.log(global.process.env);
console.error("error");
console.warn("warning");

console.log(__dirname); //当前文件所在目录
console.log(__filename); //当前文件名



console.time("label1");

setTimeout(()=>{

    console.log("helloowrl")
}, 1000);
console.timeEnd("label1"); //打印从  time 到 timeEnd 中间代码执行所耗的时间


//每隔1s, 执行以下函数
setInterval(()=>{
    console.log("run every 1 second")
}, 1000);

path

let path = require("path"); //导入path包

console.log( path.basename('/foo/bar/baz/asdf/quux.html'));

fs



const fs = require("fs"); //文件系统
let path = require("path");

fs.stat("test.txt", (err, stat)=>{

    if(err){
        console.log(err);
        return;
    }
    console.log(stat);
});

console.log("======================");


fs.readFile("test.txt", (err, data)=>{
    if(err){
        throw err;
    }

    console.log(data.toString());

});




fs.writeFile("test.txt", "hello world", (err, )=>{
    if(err){
        throw err;
    }

    console.log("wirte ok!")

});



fs.readdir("../Day1", (err, files)=>{

    //console.log(files);

    files.forEach(f =>{
        fs.stat(path.join("../Day1", f), (err, stat)=>{
            if(stat.isDirectory()){
                console.log(f, "is dir")
            }else{
                console.log(f, "is file")
            }
        })
    });


    // for(var i = 0; i <100; i++){
    //     console.log(i);
    // }

});


//删除文件
fs.unlink("test.txt", (err)=>{
    if(err){
        throw err;
    }
    console.log("delete ok");
});


//删除空目录
// fs.rmdir()



 let fse = require("fs-extra");


/*
fse.remove("testdir", err =>{
    if(err) throw err;
    console.log("delete dir ok!")
});
*/



fse.watchFile("test2.txt", (cur, pre)=>{

    console.log("cur time:" + cur.mtime);
    console.log("prev time:" + pre.mtime);

});




let fs = require("fs");


//只能读取 2G(0x7fffffff) 以下
//fs.readFile("")

let reader = fs.createReadStream("G:\\视频\\blockchain1\\06_nodejs课程\\day01\\video\\12.fs模块.mp4");
let writer = fs.createWriteStream("copy.mp4");
let len = 0;
reader.on('data', (chunk)=>{
    console.log(chunk.length);
    len += chunk.length;
    writer.write(chunk, ()=>{
        console.log("写入了一块")
    });
});


reader.on('end', ()=>{
    console.log("读完了"+ len)
});

writer.on('end', ()=>{
    console.log("写完了")
});

pipe


let fs = require("fs");



reader =  fs.createReadStream("copy.mp4" );
writer = fs.createWriteStream("copy_copy.mp4");

reader.pipe(writer);  //管道使用


writer.on('end', ()=>{

    console.log("写完了")
});

await/async

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-10 15:21
 * @descriptions:
 *
 *
 * 参考网址: https://www.cnblogs.com/SamWeb/p/8417940.html
 *          博主写的很好, 一看就明白
 *
 *
 *       Promise.resolve(value)方法返回一个以给定值解析后的Promise 对象。
 *          1.但如果这个值是个thenable(即带有then方法),返回的promise会“跟随”这个thenable的对象,
 *          采用它的最终状态(指resolved/rejected/pending/settled);
 *
 *          2.如果传入的value本身就是promise对象,则该对象作为Promise.resolve方法的返回值返回;
 *
 *          3.否则以该值为成功状态返回promise对象(即传入的是普通的值)
 *
 *
 *      注意点:
 *          1.async函数返回的是一个promise对象
 *          2.async 修饰的函数是异步执行的
 *          3.await 函数只能在 async函数中使用
 */

/*
//test1/
async function timeout() {
    return 'hello world'
}
timeout().then(result => {  //因为 async函数返回的是一个promise对象
    console.log(result);
})
console.log('虽然在后面,但是我先执行');
*/



/*
//test2/
async function timeout() {
    return 'hello world'
}
console.log(timeout());
console.log('虽然在后面,但是我先执行');
*/


/*
//test3/
async function timeout(flag) {
    if (flag) {
        return 'hello world'
    } else {
        throw 'my god, failure'
    }
}
console.log(timeout(true))  // 调用Promise.resolve() 返回promise 对象。
console.log(timeout(false));
// console.log(timeout(false).catch(err=>{
//     console.log(err);
// })); // 调用Promise.reject() 返回promise 对象。
*/



//test4/
// 2s 之后返回双倍的值
function doubleAfter2seconds(num) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(2 * num)
        }, 2000);
    } )
}

async function testResult() {
    let first = await doubleAfter2seconds(30);
    let second = await doubleAfter2seconds(50);
    let third = await doubleAfter2seconds(30);
    console.log(first + second + third);
}
testResult();





promise



let fs = require("fs");
let path = require("path");
let util = require("util");


//promise  async/await




/*
async function demo() {

    try{

    let pstat = util.promisify( fs.stat);
    let files = await pstat("test.txt");

    if(files.isDirectory()){
        console.log("files is dir")
    }else{
        console.log("files is file")
    }

    }catch (e) {
        throw e;
    }

}


demo();
*/




let promise = new Promise((resolve , reject) =>{

    console.log("构造promise");
     //err = new Error("hahah");
   // let err = null;
   // c.a = 100;
   // resolve("ok");
   //  reject("fd");

    throw new Error("构造中的异常");

    // if(err){
    //     reject(err);
    // }else{
    //     resolve("ok");
    // }
});


function ok(data) {
   console.log("ok函数");
}

function fault(data) {
    console.log("fault函数");
}


//下面三种写法都可以
//1. promise.then(ok, fault); //fault函数

//2. promise.then(ok).catch(fault); //fault函数

//3. promise.then(ok).catch(err=>{  //fault函数
//     fault(err);
// });


promise.then((data)=>{
   console.log(" ok 了");
   // c.b  = 1000;
}, (err)=>{
   console.log(" 捕获promise构造中的异常 ");
   // c.c = 99;
}).catch((err)=>{
    console.log("这是 onfulfilled 和 onRejected 函数中的异常");
});

console.log("helllllllll");






/*
结论:

    1.promise.then 有两个参数
        onfulfilled -->对应构造时的resolve, 当onfulled
        onrejected-->对应构造时的reject

    2.因为 promise.then的两个参数(函数变量) 是异步执行的,
      所以promise.then() 后面的代码会继续执行

    3.promise.then() 返回的是一个新的promise

    4.构造函数中, 需要显示调用resolve, 但是不用显示调用reject(如果在then函数中有指定, 出错时会自动调用)

    5. promise 有三种状态  Pending   fullfilled(已成功)    rejected(已失败)

              只能是  Pending 转为 其他两个状态,   不可逆!
       也就是说:  在 Promise构造中, resolve 和  reject   只能执行其中一个.

 */

http

let fs = require("fs");
let http = require("http");



let server =  http.createServer((req, res)=>{
    console.log(req.url);

    //res.writeHead(200, {'Content-Type':'application/json;charset=utf-8'}); //解决乱码问题
    res.writeHead(200, {'Content-Type':'text/html;charset=utf-8'}); //解决乱码问题

    let person = {
        name: "羊轻轻",
        age : 55
    };


    //res.end(JSON.stringify(person));

    if(req.url === "/"){
        let html = fs.readFileSync("13_http.html");
        res.end(html);
    }else if(req.url === "/a"){
        let html = fs.readFileSync("13_http_a.html");
        res.end(html);
    }
});
server.listen(9999);

http


let fs = require("fs");
let path = require("path");
let http = require("http");



http.get("http://www.baidu.com", (res)=>{

    // console.log(res.toString())

    let data = '';
    res.on('data', (chunk)=>{
        data += chunk.toString();
    });

    res.on('end', ()=>{
        console.log(data);
    });

});



//文件服务器


let http = require("http");
let fs = require("fs");
let path = require("path");



let server = http.createServer((req, res)=>{

    if(req.url === '/favicon.ico'){
        res.end("");
        return;
    }

    res.writeHead(200, {'content-type' : 'text/html; charset=utf-8'});
    showDir(req, res);

});

server.listen(5000);

function showDir(req, res) {


    let target = 'test';
    if(req.url !== '/'){
        target = req.url;
        target = target.substr(1);
    }
    console.log(target);

    fs.readdir(target, (err, files)=>{
        let str = "";
        files.forEach(f =>{
            let fpath = path.join(target, f);
            console.log(fpath);
            let stat = fs.statSync(fpath);
            if(stat.isDirectory()){
                   str += `<li><a href="${fpath}">${f}</a></li>` ;
            }else{
                str += `<li>${f}</li>`;
            }
        });
        res.end(makeHtml(str));
    });

}


function makeHtml(str) {

    return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div>
    <ul>
    ${str}
    </ul>
</div>

</body>
</html>`;


}

day2

let mathutil = require("./libs/mathutils");

console.log(mathutil.add(10 , 11));

console.log(mathutil.name);

crypto

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-09 14:17
 */

let crypto = require("crypto");

let sha256 = crypto.createHash("sha256");

sha256.update("helloworld");

console.log(sha256.digest('hex'));




//AES算法加密
let data = "helloworld";
let password = "123";
const cipher = crypto.createCipher('aes192', password);
let encrypted = cipher.update(data, 'utf-8', 'hex' );
encrypted += cipher.final('hex');
console.log(encrypted);


//AES算法解密
const  decipher = crypto.createDecipher('aes192', password);
let encrydata = encrypted;
let decrypted = decipher.update(encrydata, 'hex', 'utf-8');
decrypted += decipher.final('utf-8');
console.log(decrypted);
 

events

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-09 14:38
 * @descriptions:
 *
 */




let EventEmitter = require('events');

class MyEmitter extends EventEmitter{

}


let myEmitter = new MyEmitter();

myEmitter.on('event1', (param)=>{
    console.log("事件触发了", JSON.stringify(param));
});


setTimeout(()=>{
    myEmitter.emit('event1', {"name":"yqq", "age":"23"});
}, 2000);


spider

'use strict';

let http = require("http");
let iconv = require("iconv-lite");  //用来解码gbk
let fs = require("fs");
let cheerio = require("cheerio");
let path = require('path');





http.get("http://www.27270.com/ent/meinvtupian/", res=>{
    
    let htmlBuf = [];
    res.on('data', chunk=>{
        htmlBuf.push(chunk);
    });


    res.on('end', ()=>{
        let htmlStr = iconv.decode(Buffer.concat(htmlBuf), "gbk");
        // console.log(htmlStr);

        let imgs = [];
        imgs = ExtraDataFromHtml(htmlStr);

        DownloadImg(imgs);
    });
});






function ExtraDataFromHtml(html) {

    let $ = cheerio.load(html);
    let imgArr = $('div.MeinvTuPianBox>ul>li>a>i>img').toArray();

    let retArr = [];
    imgArr.forEach(imgObj=>{
        console.log($(imgObj).attr("src"), "\t", $(imgObj).attr("alt"));

        retArr.push({
            src:$(imgObj).attr("src"),
            title:$(imgObj).attr("alt")
        });

    });
    return retArr;
}


function DownloadImg(imgs) {

    imgs.forEach(imgObj=>{


        http.get(imgObj.src, res=>{

            let imgPath = path.join('imgs', imgObj.title + path.extname(imgObj.src));
            let writer = fs.createWriteStream(imgPath);

            res.pipe(writer);


        });


        // console.log(imgObj.src, "\t", imgObj.title);

    });

}

cheerio

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-09 15:00
 * @descriptions:
 */

let cheerio = require("cheerio");


let html = `
<div>
    <h2>哈哈哈</h2>
    <h2>嘻嘻嘻嘻</h2>
    <a href="http://www.baidu.com"> 点击跳到百度</a>
    <a href="http://www.sina.com"> 点击跳到新浪</a>
    <a href="http://www.google.com"> 点击跳到谷歌</a>
</div>
`;


let $ = cheerio.load(html);

console.log(  $('div').children().first().text() );
console.log( $('h2').text() );

console.log($('div>a').text());
console.log($('div>a').attr('href'));



//获取多个
let arr = $('div>a').toArray();
arr.forEach(obj=>{
    console.log($(obj).text());
    console.log($(obj).attr("href"));
}

day3

express

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-10 10:54
 * @descriptions:
 */

let express = require("express");
let app = express();


app.use(express.static('static'));

 app.get('/', (req, res) =>{
     res.send("hello !  this is world!");
});



app.listen(3000);

static

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-10 11:18
 * @descriptions:
 */

let express = require("express");
let app = express();


app.use(express.static('static'));



app.listen(3000);

router


'use strict';

/**
 * @author: yqq
 * @create: 2018-12-10 11:23
 * @descriptions:
 */


/*
使用  Postman 测试
 */



let express = require("express");
let app = express();

// app.use('/static', express.static('static'));

app.get('/', (req, res)=>{
    res.send('hello ' + req.method)
});

app.post('/', (req, res)=>{
    res.send('hello ' + req.method)
});

app.put('/', (req, res)=>{
    res.send('hello ' + req.method)
});

app.delete('/', (req, res)=>{
    res.send('hello ' + req.method)
});

app.listen(3000);

路径匹配

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-10 12:00
 * @descriptions:
 */

let express = require("express");
let app = express();




app.get('/ab+c', (req, res)=>{

    res.send("hello ...........");

});

app.get('/a*z', (req, res)=>{

    res.send("hello ...........");

});


app.listen(3000);

模块路由

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-10 12:07
 * @descriptions:
 */

let orderRouter =  require('./router/order');
let express = require("express");
let app = express();


app.use('/order', orderRouter);

app.listen(9999);


中间件

'use strict';

/**
 * @author: yqq
 * @create: 2018-12-10 12:32
 * @descriptions:
 */

let orderRouter =  require('./router/order');
let userRouter =  require('./router/user');
let express = require("express");
let app = express();


//应用程序级别中间件:   权限认证 , 和  拦截

app.use((req, res, next)=>{


    console.time("firstmiddleware")

    // res.send("中间件")
    console.log("第一个中间件");


    // if(req.url.startsWith('/order')){
    //     //拦截
    //     res.send("拦截了");
    // }else{
    //     next();
    // }



    //需求案例:
    //   根据用户请求是否有token参数
    //     如果有, 则表示已登录
    //     否则, 未登录
    let token = req.get('token');
    if(token){
        //已经登录
        next();
    }else{
        res.send({
            code:-1,
            msg:"当前用户没登录"
        });
        next();
    }

    console.timeEnd("firstmiddleware");

});


app.use((req, res, next)=>{

    a = 9;

    console.log("第二个中间件");
    next();

});




app.use('/order', orderRouter);
app.use('/user', userRouter);


//统一, 错误处理
//错误处理中间件, 一般放在最后注册
app.use((err, req, res, next)=>{

    console.log("出错了");

    res.send({
        code : -1,
        msg : "出错了"
    });

});

app.listen(9999);


模板

'use strict';

let express = require("express");
let app = express();




app.set('views', 'template');
app.set('view engine', 'jade'); //设置模板引擎




app.get('/', (req, res)=>{

    res.render('index', {
        pageTitle : "我是标题",
        message : "我是消息"
    });

});


app.listen(8888);

Copyright © 2002-2019 某某自媒体运营 版权所有