使用原生Nodejs搭建基本服务框架

静态服务框架搭建

有两种实现:同步与异步。

同步实现起来简洁,代码量明显少于异步实现。但当获取的资源足够多时,效率低下。

异步虽然做的操作多,但当获取的资源足够多时,使用高并发能很好的提升读取文件的效率。
开启server.js服务器后,在浏览器访问本地服务即:http://localhost:8080

  • 创建一个工程文件夹

    • 创建public文件夹
      • 创建styles文件夹(css、styl、less…文件)
      • 创建scripts文件夹(js文件)
      • 创建img文件夹(图片图标文件)
      • 创建index.html文件(用于服务器渲染首页)
    • 创建server.js文件(用于创建服务器)
  • server.js(主服务器文件)

const http = require('http');
const path = require('path');
const mime = require('mime/lite');
// mime需要npm安装

const readStaticFile = require('./readStaticFile');

const server = http.createServer();

server.on('request',async (req, res) => {
	// 使用path模块的join方法拼接路径。
    let filePath = path.join(__dirname, './public', req.url);
    try {
        let {data, mimeType} = await readStaticFile(filePath);
        res.writeHead(200, {
            'Content-Type' : mimeType + ';charset=utf-8'
        });
        res.end(await data);
    } catch (error) {
        console.log(error);
    }

}).listen(3000);
  • readStaticFile.js(属于拓展脚本文件,减少主服务器的代码量)
const path = require('path');
const fs = require('fs');
const mime = require('mime/lite'); // 用于通过后缀得到对应的类型,用于设置响应体

// 1、同步实现
// function readStaticFile(fileName) {
//     let data = '';
//     let ext = path.parse(fileName).ext;
//     let mimeType = mime.getType(ext);
//     // 1、判断传过来的文件是否存在,根目录为public
//     if (fs.existsSync(fileName)) {
//         if (ext) {
//             data = fs.readFileSync(fileName);
//         } else {
//             data = fs.readFileSync('./public/index.html')
//         }
//     } else {
//         data = 'File not found!';
//     }
//     return {
//         data,
//         mimeType
//     };
// }

// 2、异步实现
function render(file) {
    try {
        return new Promise((resolve, reject) => {
            fs.readFile(file, (err, data) => {
                if (err) {
                	// 读取文件失败说明根路径为文件夹
                    reject('你访问的路径是文件夹');
                } else {
                    resolve(data);
                }
            });
        })
    } catch (error) {
        return error;
    }
}
async function readStaticFile(fileName) {
    let data = '';
    let ext = path.parse(fileName).ext; // 拓展名提取
    let mimeType = mime.getType(ext) || 'text/html';
    // 1、判断传过来的文件是否存在,根目录为public
    if (fs.existsSync(fileName)) {
    	// 判断拓展名是否为空 不为空说明访问的是文件或文件夹
        if (ext) {
            data = render(fileName);
        } else {
            data = render(path.join(fileName, '/index.html'));
        }
    } else {
        data = '没有发现文件!';
    }
    return {
        data,
        mimeType
    };
}

module.exports = readStaticFile;
  • index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./styles/common.css">
</head>

<body>
    <img src="./img/1.jpg"/>
    <img src="./img/2.jpg"/>
    <img src="./img/3.jpg"/>
    <img src="./img/4.jpg"/>
    <img src="./img/5.jpg"/>
    <img src="./img/6.jpg"/>
    <img src="./img/7.jpg"/>
</body>

</html>
  • common.css
*{
    margin: 0;
    padding: 0;
    font-size: 14px;
}
img{
    width: 50px;
    height: 50px;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值