美文网首页
node基础

node基础

作者: k丶one | 来源:发表于2020-04-13 22:16 被阅读0次

    node做中间层的优势

    1.性能(比php,java快一点)
    2.异步IO,高并发
    3.处理数据
    4.中间多一层,安全一点

    npm包管理

    1.下载安装node后,打开命令行 npm init 初始化


    捕获.PNG
    1. npm命令

    npm install xxx 安装包
    npm uninstall xxx 卸载包
    npm install 自动安装package.json下的依赖包

    node模块

    一、 自定义模块
    • exports.a=1 导出
    • module.exports {a,b,c} 批量导出
    • require() 引入

    1.如果有路径,就去路径里面找
    2.没有的话去node_modules里找
    3.最后去node安装目录找(全局模块)

    二、全局模块

    process.env 环境变量

    三、path模块
    $ node
    Welcome to Node.js v12.16.1.
    Type ".help" for more information.
    
    >path.dirname("/node/page/index.js")   目录
    '/node/page'
     >path.basename("/node/page/index.js")  文件
    'index.js'
    > path.extname("/node/page/index.js")  后缀
    '.js'
    //path.resolve() 处理一些逻辑
    > path.resolve('/node/a/b/c','../../')   
    'D:\\node\\a'
    >pa
    
    四.fs模块
    > fs.writeFile("a.text","创建a.text",(err)=>{})  //创建了一个a.text
    undefined
    > fs.readFile("a.text",(err,data)=>{console.log(err,data)})
    undefined
    > null <Buffer e5 88 9b e5 bb ba 61 2e 74 65 78 74>  //二进制
    
    > fs.readFile("a.text",(err,data)=>{console.log(err,data.toString())}) 
     //读文件
    undefined
    > null 创建a.text
    
    五、HTTP模块

    index.js

    let http = require("http")
    http.createServer((req,res)=>{
        console.log("开启服务")
         res.end("index")
    }).listen(8888)
    
    

    node index.js 并打开localhost:8888 会返回 index

    结合fs模块返回html文件

    新建index.html随便写点东西
    index.js

    let http = require("http")
    let fs = require("fs")
    http.createServer((req, res) => {
        console.log("开启服务")
        //req.url  当前请求路径
        fs.readFile(`./${req.url}`, (err, data) => {
          if (err) {
            res.writeHead(404)
            res.end("404 not found")
          } else {
            res.end(data)
          }
        })
      })
      .listen(8888)
    

    重启服务 访问localhost:8888/index.html 会返回html内容
    一个简单的服务器搭建完成

    数据通信

    get请求

    参数放在url中,小于32k,url模块处理参数

    let params = url.parse(req.url,true)
    
    post请求

    post请求分段获取数据

    let result=[]
    req.on('data',(buffer)=>{
      result.push(buffer)
    })
    req.on('end',()=>{
      let data= Buffer.concat(result)
      console.log(data.toString())
    })
    

    相关文章

      网友评论

          本文标题:node基础

          本文链接:https://www.haomeiwen.com/subject/lsbjmhtx.html