NodeJs内置模块超详细讲解

一、fs文件系统模块

1、fs.readFile()读取文件

参数1(必):读取文件的存放路径

参数2(选):采用的编码格式,一般默认utf8

参数3(必):回调函数,拿到读取成功和失败的结果

const fs = require('fs')
fs.readFile('./hello.txt','utf8',function(err,dataStr) {
        // 如果读取成功,则err值为null
        // 如果读取失败,则err值为错误对象,dataStr值为undefined
        if(err) {
                return console.log('文件读取失败:' + err.message)
        }
        console.log('文件读取成功:' + dataStr)
})

2、fs.writeFile()写入文件

参数1(必):写入文件的存放路径

参数2(必):要写入的内容

参数3(选):采用的编码格式,一般默认utf8

参数4(必):回调函数,拿到写入成功和失败的结果

const fs = require('fs')
fs.readFile('./hello.txt','hello world',function(err) {
        // 如果写入成功,则err值为null
        // 如果写入失败,则err值为错误对象
        if(err) {
                return console.log('文件写入失败:' + err.message)
        }
        console.log('文件写入成功')
})

3、fs路径问题

描述:在操作文件时,如果提供的操作路径是相对路径,很容易出现路径动态拼接错误问题

原因:代码运行的时候,会以执行node命令时所处的目录,动态拼接出被 操作文件的完整路径

解决方案:直接提供完整的路径

// __dirname 表示当前文件所处的目录
fs.readFile(__dirname + '/hello.txt','utf8',function(err,dataStr) {
})

二、path路径模块

1、path.join()拼接路径

涉及到路径拼接的操作,都要使用path.join()方法进行处理,不要直接使用 + 进行字符串的拼接,如果拼接的路径有.就会出问题,而path.join()可以处理掉这个.

const path = require('path')
const pathStr = path.join('/a','/b/c','../','/d','/e')
console.log(pathStr) // \a\b\d\e

注意: ../会抵消前面一层路径

2、path.basename()获取路径中的文件名

参数1(必):路径字符串

参数2(选):文件扩展名

const path = require('path')
const fpath = '/a/b/c/index.html'
const fullName = path.basename(fpath)
console.log(fullName); // index.html
const nameWithoutExt = path.basename(fpath,'.html')
console.log(nameWithoutExt ); // index

3、path.extname()获取路径中的文件扩展名

参数(必):路径字符串

const path = require('path')
const fpath = '/a/b/c/index.html'
const fext = path.extname(fpath)
console.log(fext); // .html

三、http模块

用来创建web服务器的模块

1、创建最基本的web服务器

1、引入http核心模块

2、创建Web服务器实例

3、为服务器绑定request事件,监听客户端的请求

4、启动服务器

const http = require('http')
const server = http.createServer()
server.on('request',function(req,res) {
        console.log('Someone visit our web server.')
})
server.listen(8080,function() {
        console.log('server running at http://127.0.0.1:8080')
})

2、req请求对象

在事件处理函数中访问与客户端相关的数据或属性

server.on('request',(req) => {
        // req.url 是客户端请求的 URL 地址
        // req.method 是客户端的 method 请求类型
})

3、res响应对象

在事件处理函数中访问与服务器相关的数据或属性

server.on('request',(req,res) => {
        const str = `您请求的URL地址是${req.url},请求的method类型为${req.method}`
        // 调用 res.setHeader()方法设置 Content-Type 响应头,解决中文乱码的问题
        res.setHeader('Content-Type','text/html;charset=utf-8')
        // res.end()方法,向客户端响应内容
        res.end(str)
})

4、根据不同的url响应不同的内容

server.on('request',(req,res) => {
        const url = req.url
        let content = '<h1>404 Not Found</h1>'
        if(url === '/' || url === '/index.html') {
                content = '<h1>首页</h1>'
        } else if(url === '/about.html') {
                content = '<h1>关于</h1>'
        }
        res.setHeader('Content-Type','text/html;charset=utf-8')
        res.end(content)
})

原文地址:https://blog.csdn.net/m0_46613429/article/details/128545529