nodejs系列学习:http请求html/css/js-----(二)

本文介绍如何使用Node.js创建一个简单的HTTP服务器,并利用fs、path和mime模块来处理文件读取与MIME类型的映射。文章还涉及了缓存机制以提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、创建package.json文件

{
    "name":"http_file",
    "version":"0.0.2",
    "discription":" http server",
    "dependencies":{ 
        "mime":"~1.2.7"
    }

}

当前目录下执行,完成mime模块安装

npm  install

mime的js源码:在node_modules\mime下的mime.js文件看看就好

var path = require('path');
var fs = require('fs');

function Mime() {
  // Map of extension -> mime type
  this.types = Object.create(null);

  // Map of mime type -> extension
  this.extensions = Object.create(null);
}

/**
 * Define mimetype -> extension mappings.  Each key is a mime-type that maps
 * to an array of extensions associated with the type.  The first extension is
 * used as the default extension for the type.
 *
 * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
 *
 * @param map (Object) type definitions
 */
Mime.prototype.define = function (map) {
  for (var type in map) {
    var exts = map[type];

    for (var i = 0; i < exts.length; i++) {
      if (process.env.DEBUG_MIME && this.types[exts]) {
        console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
          this.types[exts] + ' to ' + type);
      }

      this.types[exts[i]] = type;
    }

    // Default extension is the first one we encounter
    if (!this.extensions[type]) {
      this.extensions[type] = exts[0];
    }
  }
};

/**
 * Load an Apache2-style ".types" file
 *
 * This may be called multiple times (it's expected).  Where files declare
 * overlapping types/extensions, the last file wins.
 *
 * @param file (String) path of file to load.
 */
Mime.prototype.load = function(file) {

  this._loading = file;
  // Read file and split into lines
  var map = {},
      content = fs.readFileSync(file, 'ascii'),
      lines = content.split(/[\r\n]+/);

  lines.forEach(function(line) {
    // Clean up whitespace/comments, and split into fields
    var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
    map[fields.shift()] = fields;
  });

  this.define(map);

  this._loading = null;
};

/**
 * Lookup a mime type based on extension
 */
Mime.prototype.lookup = function(path, fallback) {
  var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase();

  return this.types[ext] || fallback || this.default_type;
};

/**
 * Return file extension associated with a mime type
 */
Mime.prototype.extension = function(mimeType) {
  var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
  return this.extensions[type];
};

// Default instance
var mime = new Mime();

// Load local copy of
// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
mime.load(path.join(__dirname, 'types/mime.types'));

// Load additional types from node.js community
mime.load(path.join(__dirname, 'types/node.types'));

// Default type
mime.default_type = mime.lookup('bin');

//
// Additional API specific to the default instance
//

mime.Mime = Mime;

/**
 * Lookup a charset based on mime type.
 */
mime.charsets = {
  lookup: function(mimeType, fallback) {
    // Assume text types are utf8
    return (/^text\//).test(mimeType) ? 'UTF-8' : fallback;
  }
};

module.exports = mime;

2、创建server.js文件

var http=require('http');
var fs  =require('fs');
var path=require('path');
var mime=require('mime');


//缓存 减少io
var cache={}; 

//创建服务
var server=http.createServer(function(req,res){
    var filepath=false;
    switch (req.url){
        case '/':
        filepath='/public/index.html';
        break;
        default :
        filepath=req.url;
        break;
    } 
    console.log(filepath);
    var abspath='.'+filepath;
    serverStatic(res,cache,abspath);
});
//开启服务
server.listen(9001,function(){
    console.log('localhost:9001 server is started');
}) 





function rend404(response){
    response.writeHead(404,{"Content-Type":'text/plain'});
    response.write('ERROR:404 source not found.');
    response.end();
}

//文件数据服务
function rendFile(response,filePath,fileContents){  
    log('render----'+filePath);
    response.writeHead(200,{"Content-Type":mime.lookup(path.basename(filePath))});
    response.end(fileContents);
}


//提供静态文件服务
function serverStatic(response,cache,absPath){
    if(cache[absPath]){//检查文件是否在缓存中
        log('在缓存中--'+absPath);
        rendFile(response,absPath,cache[absPath]);
    }else{//不在缓存中
        fs.exists(absPath,function(exists){//检查文件是否存在
            if(exists){//存在
                fs.readFile(absPath,function(err,data){//读取文件
                    if(err){//读取失败
                        log('读取失败--'+absPath);
                        rend404(response);
                    }else{//读取成功
                        cache[absPath]=data;//添加数据到缓存 
                        rendFile(response,absPath,data);
                    }
                })
            }else{//不存在
                log('不存在--'+absPath);
                rend404(response);
            }
        });


    }

}



function log(msg){
    console.log(msg);
}

通过 fs ; path ; mime ;完成文件读取路径及类型的操作,其实看完mine.js的源码可以发现require一个mime就够了。

3、”filepath=’/public/index.html’;”剩下就是在同级目录下创建资源文件css,img , js等。(有点小问题,中文路径)

4、跑起来

node  server.js

(三)说说module(模块,重用,module.exports,域)

提供下载:http://download.youkuaiyun.com/detail/zlin3007/9567033

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mars_zhanglin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值