js在浏览器和node的区别
- 在浏览器中主要由 基础语法(es) bom dom组成
- 在node中最大的区别是node中能能操作文件,而没有dom bom
- nodejs是将谷歌的v8引擎搬到服务端 使得js能被服务器解析并可成为服务端语言
- js擅长处理字符传,而node中大量处理的是2进制,Buffer就是node内置处理二进制的一个类,可以用它的toString()方法转成字符
fs模块
读取文件、增删改查文件
const fs = require("fs")
fs.readFile(path,(err,data) => {})
fs.writeFile(path,"写入的内容",{encoding:"utf-8",flag:"a"},(err) => {})
fs.mkdir("创建的路径", (err)=>{})
fs.readdir(path,(err,res)=>{})
fs.stat(path,(err,res)=>{})
fs.unlink(path,err=>{})
fs.rmdir(path,err=>{})
fs.rename(oldpath,newpath,err=>{})
流式读取数据
fs.watchFile(path,(cur,pre)=>{})
fs.unwatchFile(path)
let readStream = fs.createReadStream(prth)
let writeStream = fs.createWriteStream(path)
readStream.on("close",(err)=>{})
writeStream.on("close",(err)=>{})
const rs = fs.createReadStream(__dirname + '/test/Until You.mp3');
const ws = fs.createWriteStream(__dirname + '/test/untiyou.mp3');
rs.pipe(ws);
rs.on('data', function (data) {
console.log('数据可读')
});
rs.on('end', function () {
console.log('文件读取完成');
});
URL模块
const URL = require('url').URL
let u = "http://fy:123456@nodejs.cn:8080/api/url?aaa=bbb#123"
let a = new URL(u)
console.log(a)
URL {
href: 'http://fy:123456@nodejs.cn:8080/api/url?aaa=bbb#123',
origin: 'http://nodejs.cn:8080',
protocol: 'http:',
username: 'fy',
password: '123456',
host: 'nodejs.cn:8080',
hostname: 'nodejs.cn',
port: '8080',
pathname: '/api/url',
search: '?aaa=bbb',
searchParams: URLSearchParams { 'aaa' => 'bbb' },
hash: '#123'
}
crypto不可逆加密模块
const crypto = require('crypto')
const pass = 'fy123456'
const hash = crypto.createHash("md5")
hash.update(pass)
let res = hash.digest("hex")
console.log(res)
http模块
const http = require("http")
http.createServer((request,response)=>{
let {url, method, headers} = request
response.writeHead(200,{
"Content-Type":"text/plain;charset=utf-8"
})
response.write("你好")
response.end()
}).listen(8080,"127.0.0.1")