用node搭建簡單的靜態資源管理器
我們都知道,老牌的3p伺服器都是自帶靜態資源管理器的。但是node不同,它沒有web容器,它的路由地址和真實地址可以沒有聯絡,所有node的優點,是可以把路由做得相當漂亮。
但靜態資源管理器也是必不可少的東西,今天我主要用node的fs模組,自己手寫一個簡單的靜態資源管理器。
首先,建一個static資料夾,所有的靜態檔案都將放到這個資料夾下
引包
var http = require("http");
var url = require("url");
var fs = require("fs");
var path = require("path");
path包是為了讀取檔案的字尾名
var extname = path.extname(pathname);
用fs讀出檔案
var http = require("http");
var url = require("url");
var fs = require("fs");
var path = require("path");
http.createServer(function(req,res) {
//得到使用者路徑
var pathname = url.parse(req.url).pathname;
//判斷此時使用者輸入的是檔案地址還是資料夾地址
//如果是資料夾地址,那麼自動請求資料夾中的index.html
if(pathname.indexOf(".") == -1) {
pathname = "index.html";
}
//擴充名
var extname = path.extname(pathname);
//把檔案讀出來
res.writeHead(200,{"Content-type":"text/html;charset=UTF-8"});
fs.readFile("./static/"+pathname,function(err,data) {
if(err) {
//如果此檔案不存在,就因該用404返回
fs.readFile("./static/404.html",function(err,data) {
res.writeHead(404,{"Content-type":"text/html;charset=UTF-8"});
res.end(data);
});
return;
//res.end('<center>伺服器傲嬌的向你丟擲了一個404錯誤</center')
};
//MIME型別,就是
//網頁檔案:ttext/html
//jpg檔案:image/jpg
getMime(extname,function(mime) {
res.writeHead(200,{"Content-type":mime});
res.end(data);
});
});
}).listen(3000,"127.0.0.1");
function getMime(extname,callback) {
fs.readFile("./static/data.json",function(err,data) {
if(err) {
throw Error("找不到data,json檔案");
return;
}
var data = JSON.parse(data);
var mime = data[extname]||"text/plain";
callback(mime);
});
/*switch(extname) {
case:".html":
return "text/html";
break;
case ".jpg" :
return "image/jpg";
break;
case ".css" :
return "text/css";
break;
}*/
}
getMime()函式的作用是給不同型別的檔案指定不同的content-type。這裡我用了兩種方法,一種是引入一個包含很多mime的json檔案,另一種是直接列舉case語句。
引入json的方法要複雜一下。你要注意怎樣傳參和怎樣去設定回撥,來避免非同步。
相關文章
- webpack簡單搭建localhost訪問靜態資源Weblocalhost
- Node.js 系列 – 搭建靜態資源伺服器Node.js伺服器
- Node.js 系列 - 搭建靜態資源伺服器Node.js伺服器
- nginx靜態資源伺服器簡單配置Nginx伺服器
- 手寫Node靜態資源伺服器伺服器
- Node之手寫靜態資源伺服器伺服器
- node搭建簡易資源伺服器伺服器
- 如何快速搭建靜態資源伺服器伺服器
- 搭建Node.js靜態伺服器Node.js伺服器
- iKcamp|基於Koa2搭建Node.js實戰(含視訊)☞ 處理靜態資源Node.js
- webpack 靜態資源管理Web
- Web靜態資源加速Web
- SpringBoot - 搭建靜態資源儲存伺服器Spring Boot伺服器
- Nginx學習之從零搭建靜態資源網站Nginx網站
- Node 學習 -- 搭建簡單的伺服器伺服器
- 靜態資源伺服器伺服器
- Websphere中靜態資源配置Web
- wordpress 加速主題的靜態資源
- 動態繫結和靜態繫結的簡單理解
- windos系統下hexo+github搭建簡單靜態個人部落格HexoGithub
- 搭建簡單的Node.js本地伺服器Node.js伺服器
- 008.Nginx靜態資源Nginx
- 多頁應用增量更新靜態資源Webpack打包方案Web
- node之搭建一個http完整的靜態伺服器(命令列工具)HTTP伺服器命令列
- 【koa2】教你如何用中介軟體koa-static-router 搭建靜態資源伺服器,實現多路由載入靜態資源伺服器路由
- 基於 Node.js 和 Vue 的高效、簡單功能強大的靜態部落格生成器。Node.jsVue
- Node.js新手上路——動手擼一個靜態資源伺服器Node.js伺服器
- Nginx配置靜態代理/靜態資源對映時root與alias的區別,帶字首對映用aliasNginx
- node: anywhere隨啟隨用的靜態檔案伺服器伺服器
- 使用 Hooks 實現一個簡單的狀態管理器Hook
- resso,世界上最簡單的 React 狀態管理器React
- Linux下建立靜態庫、動態庫以及簡單的makefileLinux
- Spring Boot 靜態資源配置 A卷Spring Boot
- SpringBoot處理靜態資源Spring Boot
- SpringBoot靜態資源訪問Spring Boot
- asp .net core 靜態檔案資源
- Golang 非主流 打包靜態資源方案Golang
- Nginx靜態資源伺服器配置Nginx伺服器