nodejs

这篇博客详细介绍了Node.js的内置模块,包括http模块、file-system文件系统、Stream、url和querystring模块等。讲解了读取文件、删除文件、模块管理和npm、YARN的使用。还探讨了Express框架下的路由、MongoDB数据库操作以及Socket编程,提供了实例代码和跨域解决方案。
摘要由CSDN通过智能技术生成

常用的内置模块

🌹1.http模块🌹

//引入原生http
const http = require('http')
//创建server服务器
const server = http.createServer(function (req, res) {
   
    // console.log("服务端处理了...")

    //需要让前端浏览器以合适的方式解析中文
    res.writeHead(200, {
    'content-type': 'text/html;charset=utf-8' })

    //需要给浏览器写内容
    res.write(`<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h2>三阶段</h2> 
    </body>
    </html>`
    )

    //需要后端给予前端响应
    res.end()
})

//需要开启端口接听
server.listen(8080)

🌹2.file-system 文件系统模块🌹

//引入fs模块
const {
    rejects } = require('assert')
const fs = require('fs')
const {
    resolve } = require('path')
//进行读写操作   异步操作readFile

封装读取指定路径path的方法

//封装读取指定路径path的方法
function getFile(path){
   
    return new Promise((resolve,reject)=>{
   
        fs.readFile(path,'utf-8',(err,data)=>{
   
            //如果读取文件没有错误
            if(!err){
   
                resolve(data)
            }
        })
        
    })
}
getFile('html/index.html').then(res=>console.log(res))
console.log(1111)
//如果在一个函数里面调用promise实例得话 可以采用async-await的语法糖
// await 就是等待的意思,等待promise实例的resolve的结果
//即时函数
(async ()=>{
   
    let res = await getFile('html/index.html') 
    console.log('res-->',res)
})()

fs.readFileSync()同步的读取文件内容

变量 = fs.readFileSync(‘文件路径’)

//fs.readFileSync()同步的读取文件内容
//如果后续代码可能出现异常,需要借助try-catch语句块将其进行包装,这样才能保证后续代码正常执行
try{
   
    const data = fs.readFileSync('html/index1.html','utf-8')
console.log(data)
}catch{
   
    console.log('出现异常了....')
}
console.log(11111)

读取文件/目录信息

fs.readdir('./', (err, data) => {
   
    console.log('data--->',data)
    data.forEach((value, index) => {
   
      fs.stat(`./${
     value}`, (err, stats) => {
   
        // console.log(value + ':' + stats.size)
        console.log(value + ' is ' + (stats.isDirectory() ? 'directory' : 'file'))
      })
    })
  }) 

删除文件

fs.unlinkSync(‘文件路径’)

fs.unlinkSync('html/index.html')

删除文件夹

//删除文件夹  (node.js中,此方法只能删除空文件夹)
fs.rmdirSync('html')

实现删除有文件的文件夹

function rmdir(dirPath){
   
        //获取该文件夹下的所有的文件
        let files = fs.readdirSync(dirPath);
        files.forEach(child => {
   
            //拼接路径
            let current = `${
     dirPath}/${
     child}`;  //html/1.html  html/abc
            let childPath = fs.statSync(current)
            //如果该文件是文件夹
            if(childPath.isDirectory()){
    //判断是文件还是文件夹
                //递归
                rmdir(current);
            }else{
   
                fs.unlinkSync(current)
            }
        })
        //删除文件夹
        fs.rmdirSync(dirPath);
    }
rmdir('html') 

改别名

fs.renameSync(‘改前’,‘改后’);

fs.renameSync('index.html','anout.html')

🌹3.Stream模块🌹

//为什么要用流的方式?默认fs读取小的文件,读到内存中去;
//如果读取大的文件,可以采用stream流的方式进行读取
//引入fs模块
const fs = require('fs')
//压缩
const zlib = require('zlib')
//创建一个gzip对象  通过这个对象 可以把某些文件进行压缩
const gzip = zlib.createGzip()

//读取文件
const readstream = fs.createReadStream('./note.txt')
//创建一个输出流  并重命名为note2.txt.zip
const writestream = fs.createWriteStream('./note2.txt.zip')

readstream   //1.以stream的方式读物note.txt文件
  .pipe(gzip)  //2.读完note.txt文件后通过gzip进行压缩
  .pipe(writestream) //3.将上面压缩后的文件名字改为note2.txt.zip压缩包

🌹4.url模块 获取query参数🌹

处理 url型的字符串
url.parse(str,true) 返回 对象 true处理query为对象 {a:1,b:2}

const url = require('url')
let urlStr = 'http://localhost:8002/aaa?username=sdfsdf&content=234234#title'
//第一种方案获取query参数
console.log(url.parse(urlStr,true))

//第二种方案获取query参数  调用searchParams.get()方法
const urlObj = new url.URL(urlStr)
console.log(urlObj.searchParams.get('username'))

实现url字符串的query参数转成{username:sdfsdf,content:234234}

//请实现url字符串的query参数转成{username:sdfsdf,content:234234}
let url = 'http://localhost:8002/aaa?username=sdfsdf&content=234234#title'
let json = {
   }  //json={username:sdfsdf,content:234234}
let urlStr = url.substring(url.lastIndexOf('?')+1)
let urlArr = urlStr.split('&')
for(let i = 0; i < urlArr.length; i++){
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值