Node.js总结

前言:

使用node前请先安装node.js,推荐编译器使用Vs Code,一切代码在node环境中运行,需了解npm,如需使用第三方模块,先进行下载,操作如下:
创建一个文件夹 在cmd中执行
npm init -y 初始化
npm i +下载内容
npm cache clean -f 清除缓存
注意事项:
使用第三方模块

  1. 新建一个文件夹,文件夹的名字非中文,名字也不要和模块名字一样.
    2.进到文件夹里面去,命令运行: npm init -y 这个命令可以理解成是初始化
    3.下载模块, 去npm官网搜索模块,用他的说明来下
    4.使用模块,去模块的官网,或者模块说明中来使用.

以下的每行代码都用注释。。整理不易。。。。。。切勿剽窃

一、Node是什么

Node是一个基 于Chrome V8弓|擎的JavaScript代码运行环境。
在 Windows PowerShell中使用命令行操作
在vs code 中右击文件,在终端中打开

二、 Node.js运行环境安装

官网: https://nodejs.org/en/

三、Node基础,ES新语法

1、第一个Node使用

function sum(num1, num2) {
    console.log(num1 + num2);
}
sum(5, 2);

2、ES6对象成员简写

let name = '小明';
let age = 18;
let gender = '男';
let obj = {
    name,
    age,
    gender,
    secor: age
}
console.log(obj);

3、对象成员展开

let fn1 = {
     name: '小明',
     age: 18,
     sing() {
         console.log('你好,我的名字是' + this.name);
     }
 }
 let fn2 = {
         sex: '男',
         adddress: '河南省'
     }
     //  console.log(fn1.sing());
 let fn3 = {
         ...fn1,
         ...fn2,
         hair: '黄色头发', // 可直接添加
         adddress: '上海' // 会替换上面的内容
     }
     //  console.log(fn3);
 let arr = [12, 5, 6, 8, 12, 5, 6, ];
 console.log([...new Set(arr)]);

四、Node内置fs模块

1、内置模块的基本使用

// 1、导包
const fs = require('fs');
// 2、调用unlink删除方法
//  第一个参数:要删除的文件路径
//  第二个参数:回调函数
fs.unlink('./temp/01_hello.txt', (err) => {
    if (err) throw err;
    console.log('已成功删除');
})

2、fs模块读取文件

// 导包
const fs = require('fs');
// 使用readFile方法读取文件
// 第一个参数:文件的路径
// 第二个参数:可选参数,读取文件的编码格式
// utf-8转换,如果直接读取的话是buffer
// 第三个参数:回调函数
fs.readFile('./temp/01_read.txt', 'utf-8', (err, data) => {
    if (err) throw err; //err是一个错误对象,如果没有错误则是null
    console.log(data); // data是读取到的文件内容
})

3、fs模块写文件

const fs = require('fs');
// 要写入的内容
// 写的内容会替换原文件内容
const data1 = `
   
    现在我又加了一些内容   
    
`;
// 参数1:文件路径,注意:如果没有这个文件夹,将会写入失败;如果没有这个文件则会自动创建这个文件
fs.writeFile('./temp/02_write.txt', data1, (err) => {
    if (err == null) {
        console.log('文件写入成功');
    } else {
        console.log('文件写入失败');
    }
})

4、同步异步

//同步操作
// console.log('你好');
// for (let i = 0; i < 50; i++) {
//     console.log(i);
// };
// console.log('小明');


// 异步操作
// console.log('及那天是你');
// setInterval(function() {
//     console.log('hahahha');
// }, 2000);
// console.log('你好吗?');

// 读取文件的操作是异步的
// console.log('今天是2020年');
// const fs = require('fs');
// fs.readFile('./temp/02_write.txt', 'utf-8', (err, data) => {
//     if (err == null) {
//         console.log(data); //最后输出
//     } else {
//         console.log(err);
//     }
// })
// console.log('7月30日');



//  读文件的同步操作
// console.log('今天是2020年');
// const fs = require('fs');
// let data1 = fs.readFileSync('./temp/02_write.txt', 'utf-8'); //同步执行
// console.log(data1);
// console.log('7月30日');

// 异步代码将会被放入事件队列中, 优先执行主要代码(同步)
// 代码的执行顺序是将同步的执行完毕后,再执行异步

const fs = require('fs');
let data1 = fs.readFileSync('./temp/02_write.txt', 'utf-8'); //同步执行
console.log(data1 + '111');
let data2 = fs.readFileSync('./temp/02_write.txt', 'utf-8'); //同步执行
console.log(data2 + '222');
let data3 = fs.readFileSync('./temp/02_write.txt', 'utf-8'); //同步执行
console.log(data3 + '333');


fs.readFile('./temp/02_write.txt', 'utf-8', (err, data) => {
    if (err == null) {
        console.log(data + '444'); //最后输出
    } else {
        console.log(err);
    }
})
fs.readFile('./temp/02_write.txt', 'utf-8', (err, data) => {
    if (err == null) {
        console.log(data + '555'); //最后输出
    } else {
        console.log(err);
    }
})
fs.readFile('./temp/02_write.txt', 'utf-8', (err, data) => {
    if (err == null) {
        console.log(data + '666'); //最后输出
    } else {
        console.log(err);
    }
})

5、同步异步面试题

<script>
        //1
        var t = true;
        window.setTimeout(function() {
            t = false;
        }, 1000);
        while (t) {}; // 卡在while里出不来,造成死循环,优先执行主要代码
        alert('end')
            //2  还是死循环,出不来,同步代码没有执行完毕
        var t = true;
        while (t) {
            window.setTimeout(function() {
                t = false;
            }, 1000);
            console.log('11');
        };
        alert('end')
    </script>

五、Node内置path模块

1、node路径问题

const fs = require('fs');
// 这里使用的是相对路径,相对于运行的小黑框而言
fs.readFile('./temp/01_tem.txt', 'utf-8', (err, data) => {
    if (err == null) {
        console.log(data);
    } else {
        console.log(data);
    }
})

2、绝对路径

const fs = require('fs');

fs.readFile('E:\\vs code\\Node.js\\03_node内置模块path\\temp\\01_tem.txt', 'utf-8', (err, data) => {
    if (err == null) {
        console.log(data);
    } else {
        console.log(data);
    }
})

3、和路径相关的两个属性

// __dirname 两个横线+dirname 获取的是当前这个文件所在整个文件夹的绝对路径
// __filename 拿到的是这个文件的绝对路径
//console.log(__dirname); //E:\vs code\Node.js\03_node内置模块path
//console.log(__filename); //E:\vs code\Node.js\03_node内置模块path\03_和路径相关的两个属性.js


// 在使用时我们通过拼接路径,来读取文件
// 原本路径 E:\vs code\Node.js\03_node内置模块path\temp\01_tem.txt
console.log(__dirname + '\\temp\\01_tem.txt');
//E:\vs code\Node.js\03_node内置模块path\temp\01_tem.txt

4、使用拼接路径来读取js文件

const fs = require('fs');
let fileFull = __dirname + '\\temp\\01_tem.txt';
fs.readFile(fileFull, 'utf-8', (err, data) => {
    if (err == null) {
        console.log(data);
    } else {
        console.log(err);
    }
})

5、path模块的基本使用

// path join方法用于拼接文件路径
const path = require('path');
const Fullpath = path.join(__dirname, 'temp', '01_tem.txt');
console.log(Fullpath); //E:\vs code\Node.js\03_node内置模块path\temp\01_tem.txt

6、使用path模块拼接的绝对路径来读取文件

// 导包
const fs = require('fs');
const path = require('path');
// 调用join方法
const Fullpath = path.join(__dirname, 'temp', '01_tem.txt');
// 读取文件
fs.readFile(Fullpath, 'utf-8', (err, data) => {
    if (err == null) {
        console.log(data);
    } else {
        console.log(err);
    }
})

六、Node内置http模块

1、创建一个服务器

// 导入http模块
const http = require('http');
//创建一个服务器
// 这个方法有一个返回值,返回值就代表这个服务器
let server = http.createServer((request, response) => {
    //返回的内容
    // response.end('study  node.js')
    // 如果想要返回的中文不乱码,要添加响应头
    response.setHeader('Content-Type', 'text/html;charset=utf-8');
    response.end('正在学习配置服务器')
});
// 开启服务器
server.listen(8087, () => {
    console.log('成功开启服务器'); //访问http://127.0.0.1:8087/
    //localhost:8087
})

2、Web服务器读取页面返回

// 导包
const fs = require('fs');
const path = require('path');
const http = require('http');
const server = http.createServer((request, repsone) => {
        // 拼接路径
        let Fullpath = path.join(__dirname, 'web', 'index.html');
        // 读取
        fs.readFile(Fullpath, 'utf-8', (err, data) => {
            if (err == null) {
                // 响应
                repsone.end(data);
            } else {
                repsone.end('404');
            }
        })
    })
    // 开启服务器
server.listen(8087, () => {
    console.log('成功开启服务器');
})

七、创建一个静态服务器

const fs = require('fs');
const path = require('path');
const http = require('http');
const server = http.createServer((request, response) => {
    console.log(request.url); // 用户请求过来的内容,里面的url包含请求的资源名字
    let Fullpath = path.join(__dirname, 'web', request.url);
    // 读取文件 服务器会根据请求的资源名字,判断类型
    fs.readFile(Fullpath, (err, data) => {
        if (err == null) {
            response.end(data)
        } else {
            response.end('404 not find')
        }
    })
})
server.listen(8086, () => {
    console.log('成功启动服务器');
})

八、Node接收get或post请求

1、接收get传过来的数据

const http = require('http');
const url = require('url');
const server = http.createServer((request, response) => {
    // console.log(request.url);///id=9
    //request是请求对象 通过request.url我们可以拿到url中的?及其后面的内容
    // 使用时要做字符串的处理
    //这里使用node中的url模块,调用他的parse方法,直接可获得{ id: '9', uername: '“小明”' }
    // 第一个参数:要处理的url
    // 第二个参数:如果是true,就返回一个对象
    let urlObj = url.parse(request.url, true);
    // 返回的对象里面有一个query属性,他也是一个对象,这个属性里面的内容就是get传递过来的参数
    console.log(urlObj.query);
    // 返回,要转换成字符串的格式
    response.end(JSON.stringify(urlObj.query))
})
server.listen(8086, () => {
    console.log('服务器成功开启....');
})

2、接收post传过来的数据

// 导入模块
const http = require('http');
const querystring = require('querystring')
const server = http.createServer((request, response) => {
    // 如何拿post传过来的参数?
    // 一点一点的拿
    // 1、创建一个容器
    // 2、给request对象一个data事件
    //事件处理程序,参数是当前这次传递过来的这一小块内容
    //
    let postData = '';
    request.on('data', (chunk) => {
        postData += chunk;
    });
    // 3、给respon对象一个end事件 表示数据传递完毕

    request.on('end', () => {
        // console.log(postData);
        // 最后调用querystring里面的parse方法解析数据
        let postObj = querystring.parse(postData);
        console.log(postObj); // { username: '小明', password: '123456' }
    })
    response.end('你正在学习node.js')
})
server.listen(8086, () => {
    console.log('成功开启服务器');
})

九、npm的使用

1、爬取图片或视频

var Crawler = require("crawler");
var fs = require('fs');

var c = new Crawler({
    encoding: null,
    jQuery: false, // set false to suppress warning message.
    callback: function(err, res, done) {
        if (err) {
            console.error(err.stack);
        } else {
            fs.createWriteStream(res.options.filename).write(res.body);
        }

        done();
    }
});

c.queue({
    //爬取小米图片
    // uri: "https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/07819effbe17e56b714e0206ec03dcfd.jpg?w=2452&h=920",
    uri: "https://ww1.sinaimg.cn/bmiddle/005vWH2Nly1gfc20yh1krg308w0754qq.gif",
    filename: "./temp/wibo.gif",
    // 如果有反爬机制,让服务端伪装成客户端(浏览器)
    //  headers: { 'User-Agent': 'requests' }
});

2、爬取整个页面

//使用第三方模块
//1. 新建一个文件夹,文件夹的名字非中文,名字也不要和模块名字一样.
// 2.进到文件夹里面去,命令运行: npm init -y 这个命令可以理解成是初始化
// 3.下载模块, 去npm官网搜索模块,用他的说明来下
// 4.使用模块,去模块的官网,或者模块说明中来使用.
var Crawler = require("crawler");
const fs = require('fs');
var c = new Crawler({
    maxConnections: 10,
    // This will be called for each crawled page
    callback: function(error, res, done) {
        if (error) {
            console.log(error);
        } else {
            var $ = res.$;
            // $ is Cheerio by default
            //a lean implementation of core jQuery designed specifically for the server
            // console.log($("title").text());
            // 爬取丁香园数据
            fs.writeFile('./temp/02.txt', $('window.getAreaStat').html(), (err) => {
                if (err == null) {
                    console.log('数据写入成功');
                }
            })
        }
        done();
    }
});

// Queue just one URL, with default callback
c.queue('https://ncov.dxy.cn/ncovh5/view/pneumonia');

十、express模块的使用(重点)

1、利用express写一个get接口

const express = require('express');
const { request, response } = require('express');
const app = express();
app.get('/jock', (request, response) => {
    let arr = ['111', '222', '888'];
    let index = parseInt(Math.random() * 3);
    response.send(arr[index]);
})
app.listen(4399, () => {
    console.log('服务器已开启....');
})

2、get请求带参数

const express = require('express');
const { request, response } = require('express');
const app = express();
app.get('/Name', (request, response) => {
    // let request.query
    let Heor = '';
    switch (request.query.username) {
        case '小明':
            Hero = '111';
            break;
        case '小花':
            Heor = 'hahha';
            break;
    }
    console.log(request.query.username);
    response.send(Heor);
})
app.listen(4399, () => {
    console.log('服务器已开启.....');
})

3、利用express写一个post接口

const express = require('express');
const app = express();
app.post('/name', (req, res) => {
    res.send('post 请求')
});
app.listen(4399, () => {
    console.log('服务器开启了。。。');
})

4、post请求带参数

//post请求要添加
// extended: false:表示使用系统模块querystring来处理,也是官方推荐的
// extended: true:表示使用第三方模块qs来处理
app.use(bodyParser.urlencoded({ extended: false }))

//由于是post方式传递过来的参数,所以用req.query这种方式是拿不到的
// console.log(req);
// console.log(req.query);
// 要想获取post参数 用使用第三方模块 body-parser
// 用req.body来获取
app.post('/login', (req, res) => {
    console.log(req.body); //{ username: '小明', password: '123456' }
    if (req.body.username == '小明' && req.body.password == '888') {
        res.send({
            code: 200,
            msg: '登录成功'
        })
    } else {
        res.send({
            code: 400,
            msg: '账户或密码错误'
        })
    }
});
app.listen(8086, () => {
    console.log('服务器已开启...');
})

5、设置一个返回json文件的接口

const express = require('express');
const app = express();
app.get('/login', (req, res) => {
    //设置一个响应头
    res.setHeader('Content-Type', 'text/json')
        //返回一个json格式的字符串
    res.send(`
        "name":"小明",
        "密码":"123456"
    `)
})
app.listen(8086, () => {
    console.log('服务器已开启....');
})

6、post请求传递一个文件

const express = require('express');
// 导入multer第三方模块
const multer = require('multer');
const app = express();

// 用包 帮你创建一个uploads这个文件夹
var upload = multer({ dest: "uploads/" })
app.post('/register', upload.single('usericon'), (req, res) => {
    //req.file 传过来的文件,参数名用usericon
    //req.body 一起传过来的文件存在upload中,参数存在body中

    console.log(req.file);
    console.log(req.body);
    res.send('哈哈')
})
app.listen(8086, () => {
    console.log('服务器已开启...');
})

十一、jsonp的使用及原理

1、jsonp的使用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function fn1(backData) {
            console.log('使用jsonp的方法');
            console.log(backData);
            // 这个实参就是后端返回的数据
        }
    </script>
    <!-- script src标签请求回来的数据都回当做js执行 -->
    <script src="http://127.0.0.1:4399/all?callback=fn1"></script>
</body>

</html>
const express = require('express');
const app = express();
app.get('/all', (req, res) => {
    // res.send(`${req.query.callback}();`);
    //用实参的方式返回数据
    // { name: '小明', age: 18 }
    res.send(`${req.query.callback}({ name: '小明', age: 18 });`);
})
app.listen(4399, () => {
    console.log('服务器已开启。。。。');
})

2、jaonp跨域请求原理

const express = require('express');
const app = express();
app.get('/login', (req, res) => {
    // res.send(`${req.query.callback}();`);
    //用实参的方式返回数据
    // { name: '小明', age: 18 }
    res.send(`${req.query.callback}({ name: '小明', age: 18 });`);


})
app.listen(8086, () => {
    console.log('服务器已开启。。。。');
})
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>点击我获得数据</button>
    <script src="./js/jquery-3.5.1.min.js"></script>
    <script>
        function fn1(backData) {
            console.log('你好吗?');
            console.log(backData);
        }
        $('button').on('click', function() {

            // 动态创建script标签
            var script1 = document.createElement('script');
            // 创建的script标签 使用jquery时不需要加引号 即$(script1)

            $(script1).attr('src', 'http://127.0.0.1:8086/login?callback=fn1');
            $('body').append(script1)
        })
    </script>
</body>

</html>

3、jquery使用ajax请求自己的接口

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button>使用jquery的ajax请求自己的接口数据</button>
    <script src="./js/jquery-3.5.1.min.js"></script>
    <script>
        $('button').on('click', function() {
            $.ajax({
                url: 'http://127.0.0.1:8086/login',
                dataType: 'jsonp',
                success: function(backData) {
                    console.log(backData);
                    //如果这个访问的接口支持jsonp,那发送ajax请求就可以使用jsonp
                    //jQuery使用jsonp,就有一个参数dataType: 'jsonp'.
                    //为什么加了这样的一个参数就可以了,
                    //他的本质(他的原理),就是自动的帮你创建一个script标签 ,用他的src属性去发送请求

                }
            })
        })
    </script>
</body>

</html>
  • 23
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 21
    评论
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值