1. 程式人生 > 其它 >[nodejs] 靜態資源伺服器

[nodejs] 靜態資源伺服器

1. 工具函式

module/file.js

讀取檔案資料

const fs = require('fs');

const readFile = (path) => new Promise((resolve) => {
  fs.readFile(path, (err, data) => {
    resolve({ err, data });
  });
});

module.exports = {
  readFile,
};

module/util.js

根據請求路徑獲取mimeType

const path = require('path');
const file 
= require('./file'); const getMimeType = async (url) => { let extname = path.extname(url); extname = extname.split('.').slice(-1).toString(); const { err, data } = await file.readFile('./module/mime.json'); const mimeTypeMap = err ? {} : JSON.parse(data); return mimeTypeMap[extname] || 'text/plain'; } module.exports
= { getMimeType, };

module/mime.json

下載地址: https://github.com/micnic/mime.json/blob/master/index.json

2.靜態路由處理函式

router/index.js

const file = require('../module/file');
const util = require('../module/util');

const static = async (req, res, staticPath = 'static') => {
  const { url } = req;
  if (url !== '/favicon.ico') {
    const filePath 
= `${staticPath}${url}`; const { err, data } = await file.readFile(filePath); if (!err) { const mimeType = await util.getMimeType(url); res.writeHead(200, { 'Content-Type': mimeType }); res.end(data); } } } module.exports = { static, };

3. sever.js

const http = require('http');
const router = require('./router/index');

http.createServer(async (req, res) => {
  await router.static(req, res); // 靜態資源伺服器

  const { url } = req;
  if (url === '/index') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ a: 1, b: 2 }));
  } else if (url === 'login') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ a: 2, b: 3 }));
  } else {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('404 page not found.');
  }
}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');