iT邦幫忙

DAY 7
8

node.js伺服器實戰系列 第 7

node.js伺服器實戰(7) - mime支援

利用node-mime模組,建立檔案類型判別的支援。
有沒有套件可用

如果只是根據副檔名來做查詢,其實速度快也不難做,只是要維護檔案類型的對應有點繁瑣。還是去找一下看有沒有人寫好的...

http://search.npmjs.org 用mime做關鍵字查詢,可以看到許多跟mime有關的套件,這裡面 http://search.npmjs.org/#/mime 看起來還不錯...

上到他的github看一下使用說明: https://github.com/bentomas/node-mime ...也蠻簡單的,而且支援大概600~800種檔案類型的樣子,就決定是它了。

使用node-mime

node-mime使用上也蠻簡單的,只要利用他提供的lookup函數,把檔案路徑丟給他做查詢,他就會返回MIME資訊,可以直接給Content-Type header使用,這樣很容易整合到流程中。稍微調整一下程式,把要用的與要測試的檔案放進來:

 .
 |-- README
 |-- deps
 |   `-- mime
 |       |-- LICENSE
 |       |-- README.md
 |       |-- index.js
 |       |-- mime.js
 |       |-- mime.types
 |       |-- node.types
 |       |-- package.json
 |       `-- test.js
 |-- lib
 |   `-- evolve.js
 `-- www
     |-- bg.gif
     `-- index.html

然後修改一下lib/evolve.js:

 var http = require('http'),
     fs = require('fs'),
     url = require('url'),
     mime = require('../deps/mime'),
     path = require('path'),
     baseDir = path.join(__dirname, '/../www'),
     server = http.createServer(function(request, response) {
         var urlObj = url.parse(request.url);
         var respath = path.join(baseDir, urlObj.pathname);
         console.log('request: ' + respath);
         fs.readFile(respath, function(err, data) { //data,就是Buffer物件
             if(err) {
                 console.log(respath + ' not exists.');
                 response.writeHead(404, '');
                 response.end();
             } else {
                 console.log(respath + ' exists.');
                 response.writeHead(200, {
                     "Content-Type": mime.lookup(respath), //只要用mime.lookup就可以取得mime type資訊
                     "Content-Length": data.length
                 });
                 response.end(data);//response.end可以傳給他Buffer物件或是字串
             }
         });
     });
 server.listen(8443, '127.0.0.1');
 console.log('server started.');

然後來試試看,打開瀏覽器,在網址列輸入 http://localhost:8443/index.html 出現this is index.html。在網址列輸入 http://localhost:8443/bg.gif ,圖片也有出現,看起來這樣修改是ok的。

另外其實還做了一點小更動,就是利用path模組來處理資源路徑,這樣可以在不同系統中產生比較合適的路徑表示。

相關文章


上一篇
node.js伺服器實戰(6) - 初步概念驗證
下一篇
node.js伺服器實戰(8) - 目錄的預設index檔
系列文
node.js伺服器實戰33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言