export default b //默认导出方式
import a from 'a.js';
export {d1,d3} //导出方式
import { d1,d2 } from 'a.js'
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
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")
})
使用方法:node server.js —> nodemon server.js | node-dev server.js
const url = require('url');
const str = "https://www.baidu.com/s?ie=UTF-8&wd=美女";
url.parse(str,flag?:boolean); //得到结果类似于location
// 第二个参数传true时,可以将?后的参数解析成object
Url {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com',
port: null,
hostname: 'www.baidu.com',
hash: null,
search: '?ie=UTF-8&wd=美女',
query: 'ie=UTF-8&wd=美女',
pathname: '/s',
path: '/s?ie=UTF-8&wd=美女',
href: 'https://www.baidu.com/s?ie=UTF-8&wd=美女'
}
url.format(Url);//https://www.baidu.com/s?ie=UTF-8&wd=美女
两个字符串拼接时替换第一个参数最后一个"/"后的内容
域名地址拼接时直接得到 域名+第二个参数
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() ;//得到WHATWG Option对象
url.parse();//得到httpOption对象 二者字段有差异
青山不改、绿水长流,江湖再见
querystring.parse()
querystring.stringify()
querystring.escape() // 处理特殊字符 例如 sql注释语句 “–”
querystring.unescape() //类似于前端 encode / unencode
req.write(
calback(${JSON.stringify({name:"",age:""})})
)
res.writeHeader(200,{‘access-control-allow-origin’:‘ip:port’})
let data = "";
https.get(url,(res)=>{
res.on('data',(chunk)=>{
data += chunk
})
res.on('end',()=>{
//todo(data)
})
})
// 作为接口服务时可用 url.searchParams.get(key)方法获取参数
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) });
典型的发布订阅模式
const EventEmmiter = require("event")
const event = new EventEmmitter()
event.on('play',(data)=>{});
event.emit("play",data)
//注意: event的监听无法卸载,避免重复绑定play事件,导致重复执行
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",{})
const readStream = fs.createReadStream(path,'utf8')
read.on("data",(chunk)=>{})
read.on("end",()=>{})
read.on("error",()=>{})
const writeStream = fs.createWriteStream()
readStream.pipe(writeStream)
关键字 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,()=>{})
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依赖包