1、基础
1.1 使用模块(module)
内建模块
const os = require("os")
第三方模块
const cpuStat = require("cpu-stat")
自定义模块
// rate.js 自定义模块
let rate;
function rmbToDollar(rmb){
return rmb/rate;
}
// 传参定义rate
module.exports = function (r) {
rate = r;
return {rmbToDollar}
}
// index.js 使用模块
const {rmbToDollar} = require('./currency')(6)
console.log(rmbToDollar(10))
2、核心API
2.1、fs
读取文件
const fs = require('fs') // 先引入内建模块
同步读取
// 同步读取、但阻塞程序(不建议使用)
const data = fs.readFileSync('./conf.js');
console.log(data)
异步读取
// readFile 自带的回调函数
fs.readFile('./conf.js', (err, data)=>{
console.log(data);
})
// promise异步方式
const {promisify} = require('util')
const readFile = promisify(fs.readFile) // 将fs.readFile包裹起来
readFile('./conf.js').then(data=>console.log(data))
// promise 新API,需nodejs v10.0以上版本
const {promises} = require('fs');
promises.readFile('./conf.js').then(data=>console.log(data.toString()))
genertor 和 async await
// 对 fs 模块进行 Promise 封装
const readFile = function (src) {
return new Promise((resolve, reject) => {
fs.readFile(src, (err, data) => {
if (err) reject(err)
resolve(data)
});
});
}
// generator
function* genertorFn(){
yield readFile('./conf.js')
yield readFile('./conf2.js')
}
var gen = genertorFn()
gen.next().value.then(data => {
console.log(data.toString()) // 显示conf.js 的内容
return gen.next().value
}).then(data => {
console.log(data.toString()) // 显示conf2.js 的内容
})
console.log('我先执行了')
// async await
async function asyncFn() {
const data = await readFile('./conf.js')
console.log(data.toString())
}
asyncFn()
2.2、Buffer
// buffer: 八位字节组成数组,可以有效的在js中存储二进制数据
// 创建(定义长度)
const buf1 = Buffer.alloc(10)
buf1.write('hello') // 如果传入汉字,一个汉字占3个字节
console.log(buf1) // <Buffer 68 65 6c 6c 6f 00 00 00 00 00>
// 从数据创建
const buf2 = Buffer.from('world')
console.log(buf2)
// 读取 toString(指定编码)
console.log(buf1.toString('utf-8')) // hello
// 合并
const buf3 = Buffer.concat([buf1,buf2])
console.log(buf3.toString())
2.3 stream
// stream 用于node中流数据的交互接口,对二进制友好
// 常用于文件的复制和传输
const fs = require('fs')
const rs = fs.createReadStream('./conf.js') // 读取流
const ws = fs.createWriteStream('./conf2.js') // 写入流
rs.pipe(ws)
2.4 http
const http = require('http')
const fs = require('fs')
const path = require('path')
http.createServer((req,res)=>{
const {url,method} = req;
// 读取首页
if (url === '/' && method === 'GET') {
// console.log(path.resolve('./index.html'));
fs.readFile(path.resolve('./index.html'), (err, data)=>{
if (err) {
res.statusCode = 500; // 服务器内部错误
res.end('500 - Internal Server Error!');
return;
}
res.statusCode = 200; // 请求成功
res.setHeader('Content-Type', 'text/html');
res.end(data);
})
} else if(url === '/users' && method === 'GET') {
// 接口编写
res.statusCode = 200; // 请求成功
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify([{name:'tom',age:20}]));
} else if(req.headers.accept.indexOf('image/*')!==-1 && method === 'GET') { // 读取图片
console.log('.'+url)
fs.createReadStream(path.resolve('.'+url)).pipe(res) // 因为res可以是流的形式,所有不需要res.end
}
}).listen(3000);
3、简单实现Express
// express.js
const http = require("http")
const url = require("url")
// 实现一个路由器
let router = [];
class Application {
get(path, handler) {
// console.log(path,handler);
router.push({
path,
method: "get",
handler
})
}
listen() {
// 创建server
http.createServer((req, res) => {
let {pathname} = url.parse(req.url, true)
console.log(url.parse(req.url, true))
for (const route of router) {
if (route.path === pathname) {
route.handler(req, res)
return
}
}
}).listen(...arguments) // arguments 指的listen的传入参数,不需要声明参数
}
}
module.exports = function (config) {
return new Application()
}
// index.js
const express = require("./express")
const app = express()
const fs = require("fs")
const path = require("path")
app.get("/", (req, res) => {
// 读取首页
// console.log(path.resolve('./index.html'));
fs.readFile(path.resolve("./index.html"), (err, data) => {
if (err) {
res.statusCode = 500; // 服务器内部错误
res.end("500 - Internal Server Error!")
return;
}
res.statusCode = 200; // 请求成功
res.setHeader("Content-Type", "text/html")
res.end(data);
});
});
app.get("/users", (req, res) => {
// 接口编写
res.statusCode = 200; // 请求成功
res.setHeader("Content-Type", "application/json")
res.end(JSON.stringify([{ name: "tom", age: 20 }]))
});
app.listen(3001)