node基础

本文介绍了Node.js的基础知识,包括方便调试的nodemon插件,OS模块,CPU统计库cpu-stat,文件系统模块fs,Buffer操作,HTTP模块的使用,以及Express框架的应用,并探讨了如何封装自己的Express应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值