Node----fs、path、url模块express框架

160 阅读7分钟

fs模块

fs模块

带Sync的就是异步的,需要传递一个回调函数 fs里的方法使用的时候,传递的路径并不是相对于本身来说的,而是相对于终端打开的地址来说的

readdirSync('path') readdir("path",(err,res)=>{})

作用:获取当前路径下文件目录 异步的回调函数中的形参,err是错误内容,res是返回的列表
+ 失败的话,err是错误内容,res是undefined + 成功的话,res是返回的列表,err是null 同步的是可以用一个变量来接收返回的值,异步的接收到的是undefined

readFileSync('path','encoding' ) readFile('path','encoding',callback)

作用:获取具体文件的内容 不设置编码格式,默认得到的就是Buffer文件流(编码)格式的数据,设置buf8,得到的结果就是字符串,例如:json、html、css等,但是对于富媒体(图片,视频,音乐等)我们读取和传输的过程就是基于Buffer文件格式操作的,所以不要设置utf8读取 同步的是可以用一个变量来接收返回的值,异步的接收到的是undefined 异步的回调函数中的形参,err,res + 失败的话,err是错误内容,res是undefined + 成功的话,res是具体文件的内容,err是null

writeFileSync('path','content',encoding) writeFile('path','content',encoding,callback)

作用:将内容覆盖到某个具体的文件中 注意:地址需要加后缀名,如果没有文件,就新增,但是如果地址没有就报错,没有返回值 异步的回调函数中的形参,err,res + 失败的话,err是错误内容,res是undefined + 成功的话,res是undefined,err是null

appendFile('path','content',callback)

作用:将一些内容追加给一个文件

copyFile('path','path',callback)

作用:将第一个文件里的内容拷贝到第二个文件里面 注意:替换型拷贝,会将原来的覆盖 异步的回调函数中的形参,err,res + 失败的话,err是错误内容,res是undefined + 成功的话,res是undefined,err是null

rmdir('path',callback)

作用:删除目录 注意:删除的时候,保证目录内没有东西,否则删除失败

mkdir('path',callback)

作用:创建目录

unlink('path',callback)

作用:删除文件

path模块

  • 作用:__dirname

获取当前模块的绝对路径

  • path.resolve()

作用:获取node执行时所在的目录 传参:当括号内传递了一个相对目录(绝对目录)的时候,就会以获取的目录为依托,拼在后面

结合promise,将其几个方法简单封装一下,使其可以连then

const fs = require("fs"),
    path = require("path"),
    obj = {};
function ismedia(pathname) {
    //获取地址,查看是否是富媒体资源,如果是的话将encoding改为null
    let encoding = 'utf8';
    let reg = /(.[A-Za-z0-9]+)$/i;
    let suffix = reg.exec(pathname) && reg.exec(pathname)[1];
    if (/^(png|jpg|jpeg|gif|svg|mp3|mp4)$/i.test(suffix)) {
        encoding = null;
    }
    return encoding;
}

['readdir', 'rmdir', 'mkdir', 'readFile', 'unlink'].map(item => {
    obj[item] = function (pathname) {
        return new Promise((resolve, reject) => {
            let newPath = path.resolve(pathname),
                encoding = ismedia(pathname), callback;
            callback = function (err, res) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(res);
            }
            if (item !== 'readFile') {
                encoding = callback;
                callback = null;
            }
            fs[item](newPath,encoding,callback);
        })
    }
});
['writeFile', 'appendFile'].map(item => {
    obj[item] = function (pathname, content) {
        return new Promise((resolve, reject) => {
            let newPath = path.resolve(pathname),
                encoding = ismedia(pathname);
                content = content ? (typeof content == "object" ? JSON.stringify(content) : content+'') : null;
                console.log(content);
            let callback = function (err, res) {
                if (err) {
                    reject(err);
                    return;
                }
                resolve(res);
            }
            fs[item](newPath, content, encoding, callback);
        })
    }
})
obj['copyFile'] = function (path1, path2) {
    return new Promise((resolve, reject) => {
        let newPath1 = path.resolve(path1),
            newPath2 = path.resolve(path2),
            callback;
        callback = function (err, res) {
            if (err) {
                reject(err);
                return;
            }
            resolve(res);
        };
        fs.copyFile(newPath1, newPath2, callback);
    })
}
module.exports = obj;

url模块

是node里的内置模块,专门用来处理URL的 ###url.parse("网址",布尔); 作用:拆分url 参数:第一个参数是网址,第二个是布尔值,如果是true,返回的值中会把quire(将传参拆分成对象),默认为false 返回值:对象,拆分后的网址

let url=require("url");
let res=url.parse("https://www.baidu.com/?tn=88093251_85_hao_pg");
console.log(res);

/* 
Url {
  protocol: 'https:',//协议
  slashes: true,//协议后边的斜杠
  auth: null,
  host: 'www.baidu.com',//域名+端口号
  port: null,
  hostname: 'www.baidu.com',//域名
  hash: null,//哈希值
  search: '?tn=88093251_85_hao_pg',//问号传参(带着?)
  query: 'tn=88093251_85_hao_pg',//传参部分
  //query: [Object: null prototype] { tn: '88093251_85_hao_pg' },
  pathname: '/',//资源路径
  path: '/?tn=88093251_85_hao_pg',//资源路径+参数
  href: 'https://www.baidu.com/?tn=88093251_85_hao_pg'//完整的url
}
*/

http/https模块

http.createServer()

作用:创建一个服务 参数:回调函数,当客户端向服务端发送请求的时候就会执行,请求几次,回函数调执行几次 + 参数回调也有两个参数,request,response, + request代表客户端给服务器的内容 + response里面是一些方法,供服务器给客户端返回内容 返回值:是个函数,函数有两个参,一个是指定的端口号,第二个是一个函数,它的作用就是当服务器启动成功以后就执行此函数

const http=require('http');
let server = http.createServer((req,res)=>{
  // 当客户端王服务端发送请求的时候,此函数就会执行,而且是你请求几次,函数就会执行几次
  console.log(11111);
  res.end('hello world');
});
server.listen(8888,()=>{
    console.log('启动成功')
})

http.createServer((request,response)=>{})中的回调函数

(request,response)=>{}

函数体中必须要传response.end(),代表响应结束,()内可以传响应的数据,传过去是响应体
request.url 客户端传过来的资源路径和参数
response.writeHead(200,{'content-type':'具体类型'}) 优先于响应体传给服务器格式,让它有准备200是状态码,不写就是浏览器自己设置,写了就是指定,writeHead是响应头

服务器返回的content-type类型叫做mime类型,每一种数据格式都会对应一种mime类型

第三方模块mime

他可以通过文件的后缀名获取到对应的mime格式

mime.getType('html');===>text/html

const http = require('http');
const fs = require('./promiseFs');
const url = require('url');
const mime = require('mime');
let server = http.createServer((req, res) => {
  // console.log(req.url); // 客户端发送的资源路径(只包含资源路径和参数)
  // 客户端的意图就是想请求index.html文件
  // '/index.html?name=1&age=2'

  // 'https://www.baidu.com/user/list'
  // 'https://www.baidu.com/index.html'
  let {
    pathname, // '/index.html'
    query
  } = url.parse(req.url, true);
  // console.log(pathname,query);
  let suffixReg = /\.([a-z0-9A-Z]+)$/;
  let suffix = suffixReg.exec(pathname) && suffixReg.exec(pathname)[1]; // 'html'

  // 如果当前的suffix的值为null,说明你这次发送的是数据请求,咱们就不要在static里读取静态资源文件了



  console.log(suffix, 25);
  let encoding = 'charset=utf8';
  // 如果当前客户端请求的资源是富媒体资源,那咱们就把不需要utf8格式转码,
  /^(jpg|png|jpeg|gif|mp3|mp4)$/i.test(suffix) ? encoding = '' : null;
  if (suffix) {
    // 介绍一个第三方的模块mime,他可以通过文件的后缀名获取到对应的mime格式内容 
    // mime.getType('后缀名');可以通过后缀名找到指定的mime类型然后进行返回
    suffix = mime.getType(suffix); // 'text/html'
    console.log(27);
    fs.readFile(`./static${pathname}`).then((result) => {
      // 服务端给客户端返回的数据一般都是字符串或者BUFFER流的格式
      res.writeHead(200, {
        // 服务端返回的content-type类型叫做mime类型,每一种数据格式都会对应有一种mime类型
        'content-type': `${suffix};${encoding}`
        //  'content-type':`text/html;charset=utf8`
      });

      res.end(result);
      // console.log(res);

    }).catch((err) => {
      console.log(39);
      res.writeHead(404, {
        'content-type': 'application/json'
      });
      res.end(JSON.stringify(err))
    })
  }
  else {
    // 这里处理的是数据请求
  }

});
// console.log(mime.getType('js'),47); // 'text/html'
// console.log(mime.getExtension('text/html'),48); // 'html'

server.listen(8888, () => {
  console.log('当前的8888端口已经启动成功');
});

express

express是一款专门为node开发设计的框架,他的出现让node写起来更加的简单

app=express();创建一个服务,返回的结果app用来操作这个服务

app.listen(8080,()=>{})创建一个端口号8080的web服务,监听端口号,创建成功执行回调

app.use(express.static('地址')); 到指定地址查找客户端需要的内容,并将其返回

相当于http.createServer('地址');

app.use((req,res,next)=>{})

request身上常用的方法
  • req.path:代表请求的路径
  • req.query:代表请求的参数,键值对格式的
  • req.body:在配合body-parser中间件的情况下,req.body存储的是请求主体传递过来的信息
  • req.method:请求类型
  • req.get:获取请求头的信息
response身上的属性和方法
  • res.end 类似于原生的end方法,结束当前的响应并返回内容,要求内容是字符串
  • res.send() 最常用的给客户端返回信息(可以传递对象//BUFFER/TXT等),基于SEND是通过响应主体返回给客户端信息
  • res.type:返回content-type的类型值
  • res.set:设置响应头信息,单个设置时候可以是[key],[value];多个设置时候要用对象
  • res.json:返回给客户端内容,只不过传递的内容可以是json对象,内部会帮我们改为JSON格式字符串
  • res.status :设置当前请求返回的状态码
  • res.redirect(301,"www.baidu.com/?tn=8003516… 永久重定向到百度`
const express=require("express");
let app=express();//创建一个服务,返回给app,app来执行
app.listen(8080,()=>{
    console.log("创建成功,端口号8080")
})

//数据api的处理
//http://127.0.0.1:8080/list?lx=pro GET
app.get("/list")

//静态资源的处理
app.use(express.static("./strtic"));//express.static("地址")在服务器拿到指定资源,并将其返回
app.use((req,res,next)=>{
    //当走到这说明,static没有找到指定资源,返回404
    //res.status(404);//返回状态吗
    //res.send("not found!");//结束内容,返回not found!相当于end
    res.redirect(301,"https://www.baidu.com/?tn=80035161_1_dg");//状态码301 永久重定向到百度
})
next(),如果没有next()下面代码不执行

app.use((req,res,next)=>{})一般放请求处理上边,相当于拦截器,里面的req与下面的app.post((req,res)=>{})中的req相通

//post请求的传参是多个,所以每次都要写req.on('data'()=>{}),与req.on('end',()=>{}),很繁琐
//那么就用这个来当拦截器,把这些都参数都集中起来,然后一起返回给下面的req
app.use((req,res,next)=>{
    let data='';
    req.on('data',item=>{
        data+=item;
    });
    req.on('end',()=>{
        req.body=data;
        next();
    })
});
req.post('/list',(req,res)=>{
    console.log(req.body);//可以拿到上面的body
})
//用第三方模块实现更简单:如下
const bodyParser=require('body-parser');
app.use(bodyParser.urlencoded({
    extende:true
}))