likes
comments
collection
share

带你入坑Nodejs(三)

作者站长头像
站长
· 阅读数 53

前言

今天是手摸手系列第三篇了感觉好难啊这种更文哈哈,需要考虑的太多了后续需要写什么种种问题废话不多说接着肝用最通俗的话,讲最难的知识点。。

1. nodejs 中的绝对路径与相对路径

1.1 相对路径的缺陷

案例: 使用相对路径在不同目录下执行读取文件操作 在 d:\node\code\http下创建 01-http.js

const http = require('http');
const server = http.createServer();
server.listen(3000, () => {
    console.log('server is running...');
});

const fs = require('fs');

server.on('request', (req, res) => {
    const url = req.url;

    if (url === '/' || url === '/index') {
        fs.readFile('./view/index.html', (err, data) => {
            if (err) {
                return res.end('404 not found');
            }

            res.end(data);
        })
    } else if (url === '/list') {
        res.end('列表页');
    } else if (url === '/detail') {
        res.end('详情页');
    } else {
        res.end('404 not found');
    }
});

执行:在不同目录下执行 01-http.js 文件

d:\node\code>node 01-http.js    //成功读取文件内容
d:\node\>node code\01-http.js    //报错
d:\node>node \code\01-http.js    //报错

执行结果: 只有第一条执行成功,其余两条都执行失败。

原因: 相对路径是以命令执行的目录作为起点的。

解决方法: 使用绝对路径

//不同url地址显示不同html页面
const http = require('http');
const server = http.createServer();
server.listen(3000, () => {
    console.log('server is running...');
});

//加载fs模块,该模块能够读写文件
const fs = require('fs');

//定义绝对路径的根目录
const rootPath = 'C:/Users/Administrator/Desktop/code/http';

server.on('request', (req, res) => {
    const url = req.url;

    if (url === '/' || url === '/index' || url === '/index.html') {
        //参数1: 要读取的文件路径,绝对路径(推荐)和相对路径
        //参数2: 字符集(可选参数, 一般都用utf-8)
        //参数3: 读取完成后触发的回调函数, 有两个参数 err和data
        const fPath = rootPath + '/view/index.html';
        //C:/Users/Administrator/Desktop/code/http/view/index.html
        fs.readFile(fPath, 'utf-8', (err, data) => {
            if (err) {
                console.log(err);
                return res.end('404 not found');
            }

            res.end(data);
        })
    } else if (url === '/list') {
        const fPath = rootPath + '/view/list.html';
        //C:/Users/Administrator/Desktop/code/http/view/list.html
        fs.readFile(fPath, (err, data) => {
            if (err) {
                console.log(err);
                return res.end('404 not found');
            }

            res.end(data);
        })
    } else if (url.startsWith('/public')) {
        //url = '/public/css/a.css';
        //url = '/public/css/c.css';
        //url = '/public/js/b.js';
        
        //C:/Users/Administrator/Desktop/code/http/public/css/a.css
        //C:/Users/Administrator/Desktop/code/http/public/css/c.css
        //C:/Users/Administrator/Desktop/code/http/public/js/b.js
        
        fs.readFile(rootPath + url, (err, data) => {
            if (err) {
                console.log(err);
                return res.end('404 not found');
            }

            res.end(data);
        })
    }
})

注意点:

  1. 定义好根路径 --- rootPath
  2. 读取文件时使用绝对路径: rootPath + 文件路径

1.2 路径变量

__dirname:获取当前文件所处目录的绝对路径

__filename:获取当前文件的绝对路径

特点: 跨平台, 自动处理路径分隔符 / 和 \

 windows:  d:\node\http\a.js

unix:  /node/http/a.js

1.3 Path模块

  1. ==join方法: 构造url地址,能够根据不同参数不同系统组装不同的文件地址==
  2. sep属性: / 或 \ , windows系统下是 \ ; 类unix系统下是 /
  3. dirname(): 获取文件路径 (不包含文件名)
  4. basename(): 获取文件名 (不包含目录路径)
  5. extname(): 获取文件后缀

join方法:

d:\node\day-2\code\03-path.js

const path = require('path');

path.join('aaa', 'bbb', 'ccc');       // windows: aaa\bbb\ccc    类unix: aaa/bbb/ccc
path.join('d:/', 'node', 'test.js');  // d:\node\test.js
path.join('d:\\', 'node/test.js');    // d:\node\test.js
path.join(__dirname, 'view', 'index.html');  // d:\node\code\view\index.html
path.join(__dirname, 'view/list.html');	     // d:\node\code\view\list.html

1.4 http创建Web服务器时的文件读取封装

核心:在res对象上挂载一个 sendFile 方法,该方法可以根据路径读取文件并将内容返回给浏览器

  1. 在res对象上增加一个 sendFile方法
  2. 只要读取文件操作就调用 sendFile 方法即可
const http = require('http');
const server = http.createServer();
server.listen(3000, () => {
    console.log('server is running...');
});

const fs = require('fs');
const path = require('path');

server.on('request', (req, res) => {
    //获取当前请求的url地址
    const url = req.url;

    //目标: 先读取文件,再将文件返回给浏览器
    res.sendFile = function (fPath) {
        fs.readFile(fPath, 'utf-8', (err, data) => {
            if (err) {
                console.log(err);
                return res.end('404 not found');
            }

            res.end(data);
        })
    }

    // __dirname: C:\Users\Administrator\Desktop\day-3\code\http
    //判断url地址的值,不同的地址读取不同的文件
    if (url === '/' || url === '/index') {
        res.sendFile(path.join(__dirname, 'view', 'index.html'));

    } else if (url === '/list') {
        res.sendFile(path.join(__dirname, 'view', 'list.html'));

    } else if (url.startsWith('/public')) {
        //url = /public/css/a.css
        //url = /public/css/c.css
        //url = /public/js/b.js
        res.sendFile(path.join(__dirname, url))

    }
})

下一篇主要讲一下 Express 这个系列文章基本就完事了有疑问的留言噢。感觉还是不满意自己这样的文章老感觉讲不清楚哎。

点赞支持、手留余香、与有荣焉,动动你发财的小手哟,感谢各位大佬能留下您的足迹。

往期精彩推荐

转载自:https://juejin.cn/post/6995733584971563021
评论
请登录