在node.js環(huán)境中加載一個網(wǎng)站

網(wǎng)站項目是在網(wǎng)上隨便找的,文件夾名稱為static

導(dǎo)入模塊

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

創(chuàng)建服務(wù)器,并在其中加載網(wǎng)站

  1. 通過http.createServer()創(chuàng)建一個服務(wù)器
const server = http.createServer(function (req, res) {}
  1. 聲明變量pathname , 格式化URL
let pathname = url.parse(req.url).pathname;
  1. 判斷請求地址
  • 當(dāng)pathname=='/' 時,通過fs.readFile()讀取首頁index.html
if (pathname == '/' || pathname == '/index') {
        fs.readFile('./static/index.html', function (err, data) {
            if (err) {
                fs.readFile('./static/404.html', function (err) {
                    if (err) throw err;
                    res.end(data);
                })
            }
            res.setHeader('Content-Type', 'text/html;charset=utf8');
            res.end(data);
        })
    }
  • else
//獲取后綴名
let suffix = path.extname(pathname);
// 聲明mime變量,等于mime值  例:text/html
let mime = getExtName(suffix);
  • 加載請求到的文件
fs.readFile('./static/' + pathname, function (err, data) {
  //響應(yīng)頭
            res.setHeader('Content-Type', mime + ';charset=utf8');
            res.end(data)
        })

完整服務(wù)器代碼

const server = http.createServer(function (req, res) {
    let pathname = url.parse(req.url).pathname;
    // console.log(pathname)
    if (pathname == '/' || pathname == '/index') {
        fs.readFile('./static/index.html', function (err, data) {
            if (err) {
                fs.readFile('./static/404.html', function (err) {
                    if (err) throw err;
                    res.end(data);
                })
            }
            // res.setHeader('Content-Type', 'text/html;charset=utf8');
            res.end(data);
            // console.log(data.toString())
        })
    } else {
        //獲取后綴名
        let suffix = path.extname(pathname);
        let mime = getExtName(suffix);
        fs.readFile('./static/' + pathname, function (err, data) {
            res.setHeader('Content-Type', mime + ';charset=utf8');
            res.end(data)
        })
    }
})

server.listen('3000', '127.0.0.1')

判斷文件類型,返回對應(yīng)的響應(yīng)頭(在服務(wù)器外部判斷)

// 上圖代碼
 res.setHeader('Content-Type', mime + ';charset=utf8');
function getExtName(suffix) {
    // console.log(suffix)
    switch (suffix) {
        case '.html':
            return 'text/html';
        case '.css':
            return 'text/css';
        case '.js':
            return 'text/javascript';
        case '.jpg':
            return 'images/jpg';
        case '.png':
            return 'images/png';
        default:
            return 'text/plain';
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容