欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用 node.js 模仿 Apache 的部分功能

程序员文章站 2022-03-26 12:12:27
首先,这个例子用到了服务端渲染的技术。服务端渲染,说白了就是在服务端使用模板引擎,这里我先简单的介绍一下服务端渲染与客户端渲染之间的区别。 服务端渲染与客户端渲染之间的区别: 客户端渲染不利于搜索引擎优化 服务端渲染可以被爬虫抓取到,而客户端异步渲染很难被爬虫抓取到(例如:AJAX) 大部分的网站既 ......

  首先,这个例子用到了服务端渲染的技术。服务端渲染,说白了就是在服务端使用模板引擎,这里我先简单的介绍一下服务端渲染与客户端渲染之间的区别。

服务端渲染与客户端渲染之间的区别:

  • 客户端渲染不利于搜索引擎优化
  • 服务端渲染可以被爬虫抓取到,而客户端异步渲染很难被爬虫抓取到(例如:ajax)
  • 大部分的网站既不是纯异步(客户端),也不是纯服务端渲染出来的,而是两者结合的
  • 例如:京东的商品列表采用的就是服务端渲染,目的是为了seo搜索引擎优化,说白了就是为了能够被搜索到,且能被爬虫抓取(搜索引擎本身也是一种爬虫)。
  • 而京东的商品评论列表为了用户体验,而且也不需要seo优化,所以才用的是客户端渲染

简单的判断内容为服务端渲染还是客户端渲染

  最简单的方法就是:

  1. 点击访问一个页面(我们这里以京东为例)
  2. 随便访问一个商品页,然后复制商品标题
  3. 然后鼠标右击点击查看网页源代码
  4. 在源代码页按 ctrl + f ,接着把复制的内容粘贴进去
  5. 能搜到就是 服务端渲染,否则的话,就是客户端渲染。

利用 art-template 模板引擎

  1. 安装: 在想要安装的目录下打开命令行工具  输入 npm install art-template, 然后它会自动生成 node_modules 目录(前提,系统已经安装了 node.js 环境)
  2. 在需要使用的文件模块中加载 art-template:
    const template = require('art-template');
  3. 就可以使用了 , 官方文档地址:

apache 部分功能实现

node.js 相关api(本例中使用):

基于http

  • createserver() : 创建一个服务器
  • on():  提供服务:对数据的服务,发请求,接收请求,处理请求,发送响应,等等
  • listen(): 绑定端口号,启动服务器

基于fs(文件系统)

  • readfile(): 读取文件(参数一为 文件路径,参数二为回调函数)
  • readdir(): 读取目录(参数一位目录路径,参数二为回调函数)

基于path(路径)

  • extname(): 获取文件后缀名
  1. 随便在一个位置建立 www 文件夹(文件名可以自己随意):
  2. 用 node.js 模仿 Apache 的部分功能
  3. 写html:
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>index of / {{title}}</title>
    </head>
    <body>
        <h1>index of / {{title}}</h1>
        <ul>
            <li><a href="/"> parent directory</a></li>
            {{each files}}
            <li><a href="/{{ $value }}">{{ $value }}/</a></li>
            {{/each}}
        </ul>
    </body>
    </html>

     

  4. node.js:
    const http = require('http');
    const fs = require('fs');
    const template = require('art-template');
    const path = require('path');
    
    const port = 5000;
    
    const server = http.createserver();
    
    server.on('request', (request, response) => {
        let url = request.url;
        let wwwdir = 'd:/www';
        fs.readfile('./template.html', (error, data) => {
            if (error) {
                return response.end('404 not found');
            }
            // 1.如何得到 wwwdir 目录列表中的文件名和目录名
            //      fs.readdir
            // 2.如何将得到的文件名和目录名替换到 template.html 中
            //      2.1 在 template.html 中需要替换的位置预留一个特殊的标记
            //      2.2 根据 files 生成需要的 html 内容
            //      模板引擎
            if (url !== '/') {
                wwwdir += url;
            }
    
            let fileend = path.extname(wwwdir);
            /**
             * 如果是文件,则访问该文件
             * 如果是文件夹,则访问里面的内容
             */
            if (fileend !== '') {
                fs.readfile(wwwdir, (error, data) => {
                    if (error) {
                        return response.end('404 not found');
                    }
                    // 获取文件后缀名(具体问题具体分析,这里我只设置 .txt 文件的 编码类型)
                    if (fileend === '.txt') {
                        response.setheader('content-type', 'text/plain; charset=utf-8');
                    }
                    if (fileend === '.jpg') {
                        response.setheader('content-type', 'image/jpeg');
                    }
                    if (fileend === '.mp4') {
                        response.setheader('content-type', 'video/mpeg4');
                    }
                    response.end(data);
                });
            } else {
                console.log(wwwdir);
                fs.readdir(wwwdir, (error, files) => {
                    if (error) {
                        return response.end('can not find this dir');
                    }
                    console.log(files);
                    // files: [ 'a.txt', 'apple', 'images', 'index.html', 'static', 'videos' ]
                    let htmlstr = template.render(data.tostring(), {
                        title: wwwdir,
                        files: files,
                    });
                    // 3.发送响应数据
                    response.end(htmlstr);
                });
            }
        });
    });
    
    
    server.listen(port, () => {
        console.log(`服务器已经开启,您可以通过 http://127.0.0.1:${port} 访问....`);
    });

     

上一篇: 大话设计-简单工厂

下一篇: