1、方便node调试程序的插件
每次修改js文件需要重新执行才能生效,安装nodemon可以监视文件改动,自动重启
npm i -g nodemon
//运行的命令
nodemon hello.js
调试node程序:
Debug-Start Debugging
2、node之OS模块
os模块提供了一些操作系统相关的使用方法
const os = require('os');
const mem = os.freemem() / os.totalmem() * 100;
// os.freemem()以整数的形式返回空闲系统内存的字节数
3、node之cpu-stat(第三方库)
//安装
//npm i cpu-stat
const cpuStat = require('cpu-stat')
cpuStat.usagePercent((err,percent) => {
console.log(`CPU占用${percent}%`)
})
4、node之fs模块
const fs = require('fs')
//1、同步读取文件
const data = fs.readFileSync('./package.json')
console.log(data.toString())
//2、异步读取文件
fs.readFile('./package.json',(err,data) => {
console.log(data.toString())
})
//3、使异步读取文件变成同步读取
const {promisify} = require('util')
const readFile = promisify(fs.readFile) //使其变成promise的方式
readFile('./package.json').then(data => {
console.log(data.toString())
})
//4、使用async await
(async () => {
const {promisify} = require('util')
const readFile = promisify(fs.readFile) //使其变成promise的方式
const data = await readFile('./package.json');
console.log(data.toString())
})()
5、Buffer
const buf1 = Buffer.alloc(10) //分配一个10字节大小的新Buffer
console.log(buf1)
const buf2 = Buffer.from([1,2,3]);
console.log(buf2);
const buf3 = Buffer.from('Buffer创建方法')
console.log(buf3.toString())
buf1.write('hello');
console.log(buf1);
const buf4 = Buffer.concat([buf1,buf3])
console.log(buf4.toString())
console.log(buf4.toJSON());
6、http模块
const http = require('http')
const fs = require('fs');
const server = http.createServer((req,res) => {
const {url,method} = req;
if(url === '/' && method === 'GET'){
fs.readFile('index.html',(err,data) => {
if(err){
res.writeHead(500,{'content-type':'text/plain;charset=utf-8'});
res.end('server error');
}else{
res.statusCode=200;
res.setHeader('content-type','text/html');
res.end(data);
}
})
}else if(url === '/users' && method === 'GET'){
res.writeHead(200,{'Content-Type':'application/json'})
res.end(JSON.stringify({name:'xia'}))
}
})
server.listen(3313)
7、express框架
const express = require('express')
const app = express()
app.get("/",(req,res) => {
res.end("helloWorld...")
})
app.get('/users',(req,res) => {
res.end(JSON.stringify({name:'abc'}))
})
app.listen(3002,()=>{
console.log('app listen at 3002')
})
8、自己封装的express
const http = require('http')
const url = require('url')
const router = []
class Application{
get(path,handler){
router.push({
path,
method:'get',
handler
})
}
listen(){
const server = http.createServer((req,res) => {
console.log(router)
const {pathname} = url.parse(req.url,true)
for(const item of router){
let {path,method,handler} = item
if(pathname === path && req.method.toLowerCase() == method){
return handler(req,res)
}
}
})
server.listen(...arguments)
}
}
module.exports = function createApplication(){
return new Application();
}