• Node.js阶段学习(一)


    使用readFile读取文件内容

    //1导入fs文件,来操作文件
    const fs = require('fs')
    //2.调用fs.readFile()方法读取文件
    //参数1:读取文件的存放路径:./files/demo1.txt
    //参数2: 读取文件时候采用的编码格式,一般默认制定utf8
    //参数3: 回调函数,拿到读取失败和成功的结果 err(失败结果) dataStr(成功结果)
    fs.readFile('./files/demo1.txt','utf8',function (err,dataStr) {
        //2.1打印失败结果,
        // 如果读取成功,err的值为null
        // 如果读取失败,则err的值为错误对象,dataStr的值为undefined
        if(err){
            return console.log('文件读取失败'+ err)
        }
        //2.2打印成功结果
        console.log('文件读取成功'+dataStr)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    使用writeFile方法向指定的文件中插入内容

    //  1.导入fs 系统模块
    const fs = require('fs')
    //  2.调用fs.writeFile() 方法,创建写入文件内容(只能用来创建文件不能用来创建路径)重复调用fs.writeFile()方法会覆盖之前的内容
    //      参数1:表示文件的存放路径:./files/demo2.txt
    //      参数2: 表示要写入的内容: kiku
    //      参数3:回调函数
    fs.writeFile('./files/demo2.txt', 'kiku',function (err) {
        //2.1 如果文件写入成功,err返回为null
        //2.2 如果文件写入失败,err的值会是一个错误对象
        // console.log(err)
        if(err){
            return console.log('文件写入失败',err)
        }
        console.log('文件写入成功')
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    路径问题处理

    问题----

    • 问题:在使用fs模块操作文件时,如果提供的文件路径是./或者…/的相对路径时,很容易出现路径动态拼接错误的问题
    • 问题出现原因: 代码在运行的时候,会执行node命令所处的目录,动态拼接出被操作文件的完整路径

    解决方案

    • 可以直接提供一个完整的文件存放路径(移植性差,不方便维护)
    const  fs = require('fs')
    fs.readFile('/Users/WebstormProjects/nodeTEST/files/demo1.txt','utf8',function (err,data) {
        if(err){
            return console.log(err)
        }
        console.log(data)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • __dirname 表示当前文件所处目录
    const  fs = require('fs')
    const path = require("path")
    // 拼接路径要用path.join,不要使用+,如果路径格式不对,会导致错误用+ '/files/demo1.txt' 和'./files/demo1.txt'不一样,path.join会直接过滤.字符
    //path.join(__dirname,'files/demo1.txt')
    //__dirname+'/files/demo1.txt'
    fs.readFile(path.join(__dirname,'/files/demo1.txt'),'utf8',function (err,data) {
        if(err){
            return console.log(err)
        }
        console.log(data)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    path.join()方法,path.basename()方法,path.extname()方法

    path.join():拼接路径

        const fs =require('fs')
        const  path =require('path')
        //注意: ../会抵消前面的路径
        const  pathStr = path.join('/a','b/c/d','../','e')
        console.log(pathStr) ///a/b/c/e
        const  pathData = path.join('/a','b/c/d','../../','e')
        console.log(pathData) ///a/b/e
        fs.readFile(path.join(__dirname,'/files/demo1.txt'),'utf8',function (err,data){
            if(err){
                return console.log(err)
            }
            console.log(data)
        })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    path.basename():获取文件名称

        //path.basename()方法可以从一个文件路径中获取文件的名称部分
        //参数1:文件路径(必传)
        //参数2:文件扩展名(非必传,如果不需要文件扩展名可传)
        //path.basename('文件路径:','文件扩展名')
        const  path= require('path')
        //定义文件的存放路径
        const fpath = '/Users/jiangdi/WebstormProjects/nodeTEST/files/demo2.txt'
        const fname = path.basename(fpath)
        console.log(fname) //demo2.txt
        const fname1 = path.basename(fpath,'.txt')
        console.log(fname1)//demo2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    path.extname():获取文件后缀名

        //path.extname()
        // 参数:文件路径(必传)
        const path = require('path')
        const fpath ='/a/b/c/index.html' //文件存放路径:/a/b/c/index.html
        const ext= path.extname(fpath)
        console.log(ext)//.html
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    创建web服务器

        // 1.导入http模块
        const http =require('http')
        //  2.创建web服务器实例
        const server = http.createServer()
        //  3.为服务器实例绑定request事件,监听客户端的请求
        server.on('request',function (req,res) {
            console.log('Someone visit our web servers.')
        })
        //  4.启动服务器:8080配置端口
        server.listen(8080,function (){
            console.log('server running at http://127.0.0.1:8080')
        })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    了解http中req请求对象和res响应

        const http = require('http')
        const server = http.createServer()
        //req是请求对象,包含了与客户端相关的数据和对象
        server.on('request', (req,res) => {
            // req.url 客户端请求的URL地址
            const url = req.url
        //    req.method 是客户端请求的method类型
            const method = req.method
            const str = `You request url is ${url} and request method is ${method}`
            console.log(str)
        //    调用res.end() ,向客户端响应一些内容
            res.end(str)
        })
        server.listen(8081, function () {
            console.log('server running at http://127.0.0.1:8081')
        })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    解决http中文乱码问题

        const http = require('http')
        const server = http.createServer()
        //req是请求对象,包含了与客户端相关的数据和对象
        server.on('request', (req,res) => {
            // req.url 客户端请求的URL地址
            const url = req.url
        //    req.method 是客户端请求的method类型
            const method = req.method
            const str = `你请求的url是 ${url} 请求的方法是 ${method}`
            console.log(str)
            // 调用 res.setHeader()方法,设置Content-Type响应头,解决中文乱码的问题
            res.setHeader('Content-type','text/html;charset=utf-8')
            // 调用res.end() ,将响应返回给客户端
            res.end(str)
        })
        server.listen(80, function () {
            console.log('server running at http://127.0.0.1')
        })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

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

        //导入http模块
        const http = require('http')
        //创建服务器
        const server = http.createServer()
        // 监听web服务器的 request 事件
        server.on('request',(req,res)=>{
        //   1.获取请求的url地址
            const url =req.url
        //   2.设置默认响应的内容为 404 not found
            let   content = '

    404 not found

    '
    // 3.判断请求是否为/或者/index.html首页 // 4. 判断页面是否为about.html 关于页面 if(url === '/' || url ==='/index.html'){ content ='

    首页

    '
    } else if(url === '/about.html'){ content ='

    关于页面

    '
    } // 5.设置Content-type响应头,防止中文乱码 res.setHeader('Content-type','text/html;charset=utf-8') // 6.使用res.end() ,把内容返回给客户端 res.end(content) }) server.listen(8081,()=>{ console.log('server is running http://127.0.0.1:8081' ) })
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

    node模块分为内置模块,自定义模块,和第三方模块

     //加载内置模块
    const fs = require('fs')
    //加载用户自定义模块要写路径 ,注意在加载自定义模块时可以省略.js后缀名
    const m1 = require('./01m')
    //加载第三方模块
    
    • 1
    • 2
    • 3
    • 4
    • 5

    模块块级作用域

    • 在自定义模块中,定义的变量,方法等成员,只能在当前模块中访问,这种模块级别等访问限制,叫做模块作用域
    • 好处:防止了全局变量污染的问题

    向外共享模块作用域的成员

    module对象

    • 在每个.js自定义模块中都有一个module对象,它里面存储了当前模块有关的信息
    console.log(module)
    
    • 1

    module.exports 对象(exports对象)

    • 在自定义模块中,可以使用 module.exports对象,将模块内的成员共享出去,供外界使用
    • 在一个自定义模块中,默认情况下,module.exports = {}
    • 在外界使用require方法导入一个自定义模块的时候,得到的就是引入的自定义模块中通过module.exports指向的那个对象
    • module.exports和exports指向同一个对象,即最总共享的对象以module.exports指向的对象为准

    新建两个js文件 demo1.js 和demo2.js

    // demo1js
    // 向module.exports 对象上挂载 username 属性
    module.exports.username ='kiki'
    // 向module.exports 对象上挂载 sayhello 方法
    module.exports.sayhello = function (){
        console.log('大家好')
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    // demo2.js
    const  demo1= require('./demo1')
    console.log(demo1) // { username: 'kiki', sayhello: [Function (anonymous)] }
    
    • 1
    • 2
    • 3
    • 使用require 方法导入模块时,导入的结果永远以 module.exports 指向的对象为准
    • 为了防止混乱,建议大家不要在同一个模块同时使用exports 和 module.exports

    nodejs中的模块化规范(nodejs遵循了CommonJS规范)

    • 每个模块内部module 变量代表当前模块
    • module 变量是一个对象,它的 exports 属性(即 module.exports)是对外的接口
    • 加载某个模块,其实就是加载这个模块的module.exports属性,require()方法用于加载模块

    npm包

    • 命令: npm i 名称,例如npm i moment ,(npm i 和npm install 一样)
    • 使用: 1.导入的名称就是安装包的名称(require(‘moment’)):

    npm 初次安装包多了哪些文件呢

    • node_modules 文件夹用来存放所有已经安装到项目中的包,require()导入第三方包时,就是从这个目录中查找并加载包
    • package-lock.json 配置文件用来记录node_modules目录下每一个下载包的下载信息,例如包的名字,版本号和下载地址等
    • package.json(必须存在)

    npm包管理配置文件(package.json)

    • package.json 用来记录与项目有关的配置信息

    快速创建 package.json

    • 命令: npm init -y
    • 注意:此命令只能在英文的目录下成功运行,所以项目文件夹名称不能是中文,不能用空格

    如何安装指定版本的包呢?

    • 如果需要安装指定版本的包,可以在包名字之后通过 @符号 指定具体的版本,例如 npm i moment@2.29.4
    • 包的语义化版本 例如2.29.4 第一位数字:大版本,第二位数字:功能版本,第三位数字:bug修复版本
    • 版本号提升的规则:只要前面的版本号增长了,后面的版本号归零

    npm一次性安装所有的包

    • npm install (npm i)

    npm 卸载包

    • 使用npm uninstall 具体的包名 来卸载包
    • npm uninstall moment (moment是卸载的包名 )

    安装全局包

    • npm i 包名 -g

    卸载全局包

    • npm uninstall 包名 -g

    解决下载包慢的问题

    • 淘宝npm镜像
    • 查看当前下载包的镜像源 : npm config get registry
    • 将下包的镜像设置为淘宝镜像: npm config set registry https://registry.npm.taobao.org

    规范的包结构

    • 必须以单独的文件存在
    • 包的顶级目录下面必须包含package.json 配置文件
    • package.json 文件必须包括 name ,version, main 三个属性 分别代表包的名字。版本号,包的入口

    发布npm包

    • npm publish (注意:此命名在发布包的目录下)

    删除已发布的包

    • 命令:npm unpublish 包名 --force 即可删除npm发布的包
    • 注意:

    npm unpublish命令只能删除72小时以内发布的包
    npm unpublish 删除的包在24小时内不能重复发布
    尽量不要往npm发布无用包

    nrm 工具

    • 安装nrm 工具: npm i nrm -g
    • 查看所有可用的镜像源: nrm ls
    • 切换镜像 例如切换为淘宝镜像:nrm use taobao
  • 相关阅读:
    Unload-labs-pass-04
    【刷题笔记9.24】LeetCode:只出现一次的数字
    RabbitMQ部署指南
    Luma AI如何注册:文生视频领域的新星
    【C++杂货铺】探索stack和queue的底层实现
    Request&Response有这一篇就够了
    【Rust日报】2023-09-28 egui 0.23 发布
    外贸新人最全面的领英Linkedin开发客户方法(建议收藏)
    Vue学习第26天——vuex中的模块化和命名空间的详解及案例练习
    如何利用TSINGSEE青犀智能分析网关算法从人员、设备、行为三大角度进行监狱智能化升级改造
  • 原文地址:https://blog.csdn.net/xxz_best/article/details/126610445