码迷,mamicode.com
首页 > Web开发 > 详细

Node.js最简单的静态文件服务器

时间:2016-01-08 23:24:48      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

首先感谢下面代码的提供者 非常感谢!让我有这次学习的机会!

var http = require(‘http‘);
var url = require(‘url‘);
var fs = require(‘fs‘);
var util = require(‘util‘);

var mimetype = {
  ‘txt‘: ‘text/plain‘,
  ‘html‘: ‘text/html‘,
  ‘css‘: ‘text/css‘,
  ‘xml‘: ‘application/xml‘,
  ‘json‘: ‘application/json‘,
  ‘js‘: ‘application/javascript‘,
  ‘jpg‘: ‘image/jpeg‘,
  ‘jpeg‘: ‘image/jpeg‘,
  ‘gif‘: ‘image/gif‘,
  ‘png‘: ‘image/png‘,
  ‘svg‘: ‘image/svg+xml‘
}

var page_404 = function(req, res, path){
    res.writeHead(404, {
      ‘Content-Type‘: ‘text/html‘
    });
    res.write(‘<!doctype html>\n‘);
    res.write(‘<title>404 Not Found</title>\n‘);
    res.write(‘<h1>Not Found</h1>‘);
    res.write(
    ‘<p>The requested URL ‘ +
     path + 
    ‘ was not found on this server.</p>‘
    );
    res.end();
}

var page_500 = function(req, res, error){

    res.writeHead(500, {
      ‘Content-Type‘: ‘text/html‘
    });
    res.write(‘<!doctype html>\n‘);
    res.write(‘<title>Internal Server Error</title>\n‘);
    res.write(‘<h1>Internal Server Error</h1>‘);
    res.write(‘<pre>‘ + util.inspect(error) + ‘</pre>‘);
}


http.createServer(function (req, res) {
    //返回url端口号后面的的url值
    //比如:http://localhost:1337/a.html 则为/a.html
    var pathname = url.parse(req.url).pathname;
    //__dirname返回web项目的物理路径
    var realPath = __dirname +  "/static" + pathname;
    fs.exists(realPath, function(exists){
      if(!exists){
          return page_404(req, res, pathname);
      } else {
          //fs的createReadStream函数,返回ReadStream对象
          var file = fs.createReadStream(realPath);
          res.writeHead(200, {
             ‘Content-Type‘: mimetype[realPath.split(‘.‘).pop()] || ‘text/plain‘
          });
          file.on(‘data‘, res.write.bind(res));
          file.on(‘close‘, res.end.bind(res));      
          file.on(‘error‘, function(err){
              return page_500(req, res, err);
          });
        }    
    });  
}).listen(1337, ‘127.0.0.1‘);
console.log(‘Server running at http://127.0.0.1:1337/‘);

 

Node.js最简单的静态文件服务器

标签:

原文地址:http://www.cnblogs.com/chenjianxiang/p/5115038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!