• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

node常用api

武飞扬头像
凉菜凉凉
帮助1

一、两种模块化写法

  1. es6的模块化
    v13以后的版本中支持了es6的模块化引入方法,即export / import
export default b  //默认导出方式
import a from 'a.js';
export {d1,d3}	  //导出方式
import { d1,d2 } from 'a.js'
  1. commonJs规范
    默认使用require / module.export
export.b = b;    //导出方式一
const {b} = require('b.js');

module.exports = {b,c}; //导出方式二
const { b } = require('b.js');

package.json中需要增加type:"module"指明,且不可以省略.js后缀

{
	type:"module",//commonJs(默认)  |  module(es6的模块化)
}

温馨提示:module和comonJS不能同时支持,由于大多数第三方包使用commonJS模块化,为避免麻烦,谨慎使用module

二、内置模块

1.http模块

FeHelper 自动解析json格式数据的chrome插件

创建一个服务

	const http = require(""http);
	http.createServer((req,res)=>{
		res.writeHead(200,{'Content-type':'text/html;charset=utf-8'});//text/plain 普通文本格式,
		res.write("");//仅支持  string | buffer | unit8Array 这些格式
		res.end("");//必须要有end()来结束请求  string | buffer | unit8Array 这些格式
	}).listen(3000,()=>{
		console.log("server start")
	})

2.URL模块

  1. 自动重启 nodemon 、node-dev 两个工具任选其一

使用方法:node server.js —> nodemon server.js | node-dev server.js

format / parse (废弃)

const url = require('url');
const str = "https://www.百度.com/s?ie=UTF-8&wd=美女";
url.parse(str,flag?:boolean); //得到结果类似于location
// 第二个参数传true时,可以将?后的参数解析成object
Url {
  protocol: 'https:',
  slashes: true,
  auth: null,
  host: 'www.百度.com',
  port: null,
  hostname: 'www.百度.com',
  hash: null,
  search: '?ie=UTF-8&wd=美女',
  query: 'ie=UTF-8&wd=美女',
  pathname: '/s',
  path: '/s?ie=UTF-8&wd=美女',
  href: 'https://www.百度.com/s?ie=UTF-8&wd=美女'
}
url.format(Url);//https://www.百度.com/s?ie=UTF-8&wd=美女
学新通

resolve拼接url (废弃)

两个字符串拼接时替换第一个参数最后一个"/"后的内容
域名地址拼接时直接得到 域名 第二个参数

let a = url.resolve("/one/two","four");// one/four
let b = url.resolve("/one/two/",'four');// one/two/four
let c = url.resolve("http://example.com/aaa/bbb",'four');// http://example.com/four

new URL(“/path”,“http://127.0.0.1:8888”)

new URL() ;//得到WHATWG Option对象
url.parse();//得到httpOption对象 二者字段有差异
  • URLSearchParams 类
    • 可以用of遍历
    • 集成了一些方法append、delete、get 、getAll、set等
  • pathToFileURL(path) \ fileURLToPath(url) 系统盘文件路径,注:必须要绝对地址
  • urlToHttpOption(url)

queryString

青山不改、绿水长流,江湖再见

querystring.parse()
querystring.stringify()
querystring.escape() // 处理特殊字符 例如 sql注释语句 “–”
querystring.unescape() //类似于前端 encode / unencode

3.http补充

jsonp

req.write(calback(${JSON.stringify({name:"",age:""})}))

cors

res.writeHeader(200,{‘access-control-allow-origin’:‘ip:port’})

http.get

let data = "";
https.get(url,(res)=>{
	res.on('data',(chunk)=>{
		data  = chunk
	})
	res.on('end',()=>{
		//todo(data)
	})
})
// 作为接口服务时可用 url.searchParams.get(key)方法获取参数

http.request

let data = "";
const option = {
	hostname:"www.m.com",
	port:"443",//https默认443
	path:"/api/list",
	method:"post",
	headers:{
		"Content-Type":"x-www-form-urlencoded";//application/json
	}
};
const request = http.request(option,(res)=>{
	res.on('data',(chunk)=>{
		data =chunk
	})
	res.on('end',()=>{
		//todo(data)
	})
})
request.write('name=12&time=2022-01-02')
request.end()

/* 补充:
	http.createServer服务,接收post传递参数时也需要监听data,用chunk进行分段接收
 */
http.createServer((req,res)=>{ //post请求时
	let data = "";
	res.on('data',chunk=>{
		data  = chunk
	})
	res.on('end',()=>{
		data = JSON.parse(data)
		// to do ...
	})
})
学新通

fetch(“url”).then(response=>response.json()).then(res=>{ todo(res) });

4.event

典型的发布订阅模式

const  EventEmmiter = require("event")
const event = new EventEmmitter()
event.on('play',(data)=>{});
event.emit("play",data)
//注意: event的监听无法卸载,避免重复绑定play事件,导致重复执行

5.fs

	fs.writeFile
	fs.appendFile
	fs.readFile
	fs.mkdir
	fs.rmdir
	fs.readdir
	fs.stat
	fs.unlink
	fs.existsSync 是否存在
	fs.XXXSync  // 同步
	const fs = require('fs').promise // promise版
	#注意异步删除
	rmdir("./mulu",{})

6.stream

const readStream = fs.createReadStream(path,'utf8')
read.on("data",(chunk)=>{})
read.on("end",()=>{})
read.on("error",()=>{})
const writeStream = fs.createWriteStream()
readStream.pipe(writeStream)

7.zlib

关键字 zlib.createGzip() 、Content-Encode:gzip 、pipe

const zlib = rquire('zlib')
const fs = require('fs')
const http = require('http')
const gzip = zlib.createGzip()

http.createServer((req,res)=>{
	const readStream = fs.createReadStream('your files.xxx')
	res.writeHead(200,{
		'Content-Type':'text/plain;charset=utf-8',
		'Content-Encode':'gzip'
	})
	//1. readStream.pipe(res);  
 	//2. readStream.pipe(gzip).pipe(res); //经过gzip压缩后明显小于未压缩前
}).listen(3000,()=>{})

8.crypto

md5 、hmac、对称加密aes
注:hex 代表16进制 、binary: 二进制流

const crypto = require("crypto")
/* md5 */
cosnst hash = crypto.createHash('md5');
hash.update("内容");
const res = hash.digest('hex')
/* hmac*/
const hmac = crypto.createHmac("sha256","123456");//type,key
hmac.update('')
hmac.digest('hex');//输出十六进制数据
/* aes 对称加密*/

function encrypt(key,iv,data){
	let dep = crypto.createCipheriv('aes-128-cbc',key,iv)//aes-128-cbc为其中的一种128位算法
	return dep.update(data,'utf-8','hex')   dep.final('hex');//输入utf-8数据,输出16进制
}
function decrypt(key,iv,decrypted){
	decrypted = Buffer.from(decrypted,'hex').toString('binary') //转换为二进制
	let dep = crypto.createDeCipheriv('aes-128-cbc',key,iv)//与加密保持一致
	return dep.update(decrypted,'binary','utf-8') dep.final('utf-8')
}
// aes-128-cbc 128位存储 128/8 = 16 ,则key和iv 需要16个字符
const key = "1234567890qweasd"
const iv  = "qweasd1234567890"
const str = "大漠孤烟直,长河落日圆"
const crypted = encrypt(key,iv,str)
//c9f6f19404f73db3b5f021d8d2d9209bae9a3f761ef56f1d203deca29186cd69dc76aef5af145598ca4e151f08bbabaa
const res = decrypt(key,iv,crypted)
//大漠孤烟直,长河落日圆
学新通

简单实现静态资源服务器

server.js

const Router = {}

function use(router){
    return Object.assign(Router,router)
}

function start(port){
    const server = http.createServer((req,res)=>{
        const myUrl = new URL(req.url,'http://127.0.0.1');
        if(Router[myUrl.pathname]){
            Router[myUrl.pathname](req,res)
        }else{
            Router['/404'](req,res)
        }
    
    })
    
    server.listen(port,() => {
        console.log('server is running');
    })
}
export.start = start
export.use = use

学新通

route.js

function render(pathname,res,type,code=200){
    const file = fs.readFileSync(pathname);
    res.writeHeader(code,{'Content-Type':`${type?type:'text/html'};charset=utf-8`})
    res.write(file)
    res.end()
}

function getPathname(url){
    let suffix = url.split('.')[1];
    let pathname = "";
    // 1. 是否存在文件
    // 2. 是否有文件后缀,有后缀认为是静态文件,无后缀则认为是文件夹 走index.html或404
    if(suffix){//文件
        pathname = path.join(__dirname,"/static",url)
    }else{// 文件夹 ->默认走index.html
        pathname = path.join(__dirname,"/static",url,"index.html")
    }
    return {pathname,suffix}
}

const router = {
    '/404':((req,res)=>{
        const myUrl = new URL(req.url,'http://127.0.0.1')
        const {pathname,suffix} = getPathname(myUrl.pathname);//处理文件夹的情况,拼上index.html
        // 渲染
        if(fs.existsSync(pathname)){//存在文件
            render(pathname,res,mime.getType(suffix))
        }else{
            pathname = path.join(__dirname,'/static/404.html')
            render(pathname,res,mime.getType(suffix),404)
        }
    })
}

module.exports = router
学新通

api.js

const api = {
	'/api/XXX':(req,res)=>{res.end()}
}
module.exports = api

app.js

const server = require('./server.js')
const route require('./route')
const api = require('./api')

server.use(route)
server.use(api)
server.start(3001)

mime :获取content-type的一个npm依赖包

  • 做个俗人,加油

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhggaeef
系列文章
更多 icon
同类精品
更多 icon
继续加载