node.js常见的模块
Stream 流
* 什么是流? Node中為什么要有流這個概念 ? 使用場景?
* 流指的是數據流,指的是數據是分片傳輸。
* 數據可以實現非阻塞。
* gulp 【 流式操作 】
* 案例: 打包壓縮包
* 流程:
* 1. 讀取文件
* 2. 創建壓縮包
* 3. 將讀取的數據流寫入壓縮包
* 4. 輸出壓縮包
const fs = require ( 'fs' ) //引入內置模塊
const zlib = require ( 'zlib' ) //內置模塊
const inp = fs.createReadStream( './文件名.tet' ) //用fs 讀取文件
const gzip = zlib.createGzip() //創建壓縮包
const out = fs.createWriteStream( './文件名.tet.gz' )
inp
.pipe(gzip)
.pipe(outp)
Node,js常用內置模塊
1.讀取文件:fs
讀取文件都是二進制流:①:Buffer ②:binary //二進制2中名稱
const fs = require( 'fs' )
fs.readFile('./yyb.txt',( error, docs ) => {
console.log( docs.toString() ) //toString() 轉成二進制文件 中文
})
fs.readFile('./yyb.txt','utf8',( error, docs ) => { //utf8 轉成二進制文件 中文
console.log( docs )
})
2.壓縮文件:zlib
const zlib = require ( 'zlib' )
3.http模塊
①http.get
②http.request
數據接口地址:‘http://api.k780.com/app=weather.city&cou=1&appkey=43880
&sign=6a31f4fe1408d69bb0417b046eeae5b6&format=json’
const http = require( 'http' )
http.get('數據接口地址', (res) => {
const { statusCode } = res; // 獲取請求狀態碼 200 301 302 303 304 404 500...
const contentType = res.headers['content-type']; // 獲取請求類型數據類型
// json數據的content-type 'content-type': 'application/json'
let error;
if (statusCode !== 200) { // 如果狀態碼不是200 ,輸出報錯信息
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) { //驗證是否是josn格式
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) { // 如果報錯了,將報錯信息存入日志
console.error(error.message);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8'); // 字符編碼
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; }); // 通過data事件拼接數據流
res.on('end', () => { // 獲取數據結束了
try { // 高級編程語法 捕獲錯誤信息
console.log( rawData );
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
后端服務器:
①:web服務器 靜態服務器
②:api服務器 暴露接口
* 請求頭部報文
1. general //請求基本信息
2. response Headers //響應頭
3. request Headers //請求頭
4. 攜帶參數
- query string paramters //get請求
- form data //post 請求
const http = require ( 'http' )
const host= 'localhost' //主機名
const port = 8000 //端口
http.createServer( ( request , response) =>{
//response.writeHead( 狀態碼 , 請求頭 )
response.writeHead( 200 , {
'Content-type': 'text/html;charset=utf8' //轉化成中文
})
response.write( ' 這是使用node創建的一個靜態服務器' ) //往前端發送數據
response.end() // 告訴前端信息已經結束了
}).listen( port , host , () = >{
console.log( `The server is running at: http://${ host }:${ port }` )
})
http模塊:爬蟲
* 去某一個網站爬取一段數據 -> 數據清洗 -> 后端服務器 -> 發送前端 -> 渲染數據
* 不是所有網站都可以爬取
* 反爬蟲 //文字里插入圖片等方法
* 爬蟲: 后端渲染的網站
const http = require ( 'http' )
const cheerio = require( 'cheerio' ) //爬取數據
const options = {
hostname: '域名',
port: 80, //端口
path: '域名后面的路徑',
method: 'GET',
headers: {
Accept: ' ',
'Accept-Encoding': ' ', //設置返回的編碼方式
'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control':' no-cache',
Cookie: ' ',
Host: ' ',
Pragma: 'no-cache',
'Proxy-Connection': 'keep-alive',
Referer: ' ',
'Upgrade-Insecure-Requests': 1,
'User-Agent':' ',
'Content-Type': ' ',
'Content-Length': 0
}
}
http.get( options, (res) => {
const { statusCode } = res; // 獲取請求狀態碼 200 301 302 303 304 404 500
const contentType = res.headers['content-type']; // 獲取請求類型數據類型
res.setEncoding('utf8'); // 字符編碼
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; }); // 通過data事件拼接數據流
res.on('end', () => { // 獲取數據結束了
try { // 高級編程語法 捕獲錯誤信息
// console.log( rawData )
const $ = cheerio.load( rawData ) //爬取到的數據
$(' this').each(function (index,item) {
console.log( $( this ) ) //輸出數據
})
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
4.event模塊
Node.js中 事件的發布 + 事件的訂閱 表示一個任務的執行。
const Events = require( 'events' )
const fs = require( 'fs' )
const http= require( 'http' )
const host = 'localhost'
const port = 3000
class myEvent extends Events {} //類的繼承
const myevent=new myEvent() //實例化得到的一個實例
//事件的發布
// myevent.on(事件名稱,事件的回調函數)
myevent.on('aa',function () { // 書寫任務 ‘aa’ 任務名
// 任務: 將文件.txt中的內容發送前端
http.createServer( ( req,res ) => {
res.writeHead( 200,{
'Content-Type': 'text/html;charset=utf8'
})
// 1
fs.readFile('./yyb.txt','utf8',( error,docs ) => { // error作為第一個參數的回調函數,我們叫做錯誤優先的回調函數
res.write(`<h3> ${ docs } </h3>`)
res.end()
})
// 2
// why? 錯誤?
// res.end() 上面回調函數,不在主線程在任務隊列,代碼會先執行2 在執行1,所以 res.end()要放上面
}).listen( port,host,() => {
console.log( `服務器運行在: http://${ host }:${ port }` )
})
})
// 事件的訂閱
myevent.emit( 'aa' ) // ’aa‘事件的名稱
5.后端 api服務器
Node.js中api服務器的創建,我們使用一個第三方庫 express
后端解決跨域問題:
1. 設置請求頭
2. 使用中間件
第三方的包 cors
舉例:
const express = require( 'express' )
const app = express() //得到一個app對象
const port =3000
const host = 'localhost'
const cors = require( ' cors' )
//解決跨域第一種方法創建接口,設置一次即可。
app.use(cors({
"origin": " * " ,
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 200
})
app.get( ' /person' , (reg , res , next) =>{ // 回調函數我們稱之為:中間件具有 特定功能的一個函數
res.setHeader('Access-Control-Allow-Origin', '*'); // 解決跨域第二種解決辦法 設置請求頭跨域,麻煩,每個請求都得設置
res.json({
id : 1 ,
name : ' 張三' ,
age : 100
})
})
// 創建api服務器,并監聽這個服務器
app.listen( port , host , () =>{
console.log( `The server is running at : http://${ host }:${ port }` )
})
6.方向代理
1. 后端請求數據
2. 將數據發送給前端 api服務器 express
const request = require( 'request' )
const express = require( ' express' )
const host = 'localhost'
const port = 3000
const app = express()
const url = 'https://m.lagou.com/listmore.json'
//創建接口
app.get( '/position' , ( req , res , next ) =>{
res.setHeader('Access-Control-Allow-Origin', '*');
// 數據請求
request( url , (error , response , body) =>{
res.json( JSON.parse( body ) )
})
})
app.listen(port , host, () => {
console.log( `The server is running at: http://${ host }:${ port }` )
})
轉載于:https://www.cnblogs.com/zhouying-01/p/11196986.html
超強干貨來襲 云風專訪:近40年碼齡,通宵達旦的技術人生總結
以上是生活随笔為你收集整理的node.js常见的模块的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [译]Vulkan教程(32)生成mip
- 下一篇: vector-空间增长