1、nodeJS版
var http=require('http');
var fs=require('fs');
var url=require('url');
var path=require('path');
var PORT=9090;
//添加MIME类型
var MIME_TYPE = {
"css": "text/css",
"gif": "image/gif",
"html": "text/html",
"ico": "image/x-icon",
"jpeg": "image/jpeg",
"jpg": "image/jpeg",
"js": "text/javascript",
"json": "application/json",
"pdf": "application/pdf",
"png": "image/png",
"svg": "image/svg+xml",
"swf": "application/x-shockwave-flash",
"tiff": "image/tiff",
"txt": "text/plain",
"wav": "audio/x-wav",
"wma": "audio/x-ms-wma",
"wmv": "video/x-ms-wmv",
"xml": "text/xml"
};
var server = http.createServer(serverStatic);
function serverStatic(req,res){
var filePath;
if(req.url==="/"){
filePath ="index.html";
} else{
filePath = "./" + url.parse(req.url).pathname;
}fs.exists(filePath,function(err){
if(!err){
send404(res);
}else{
var ext = path.extname(filePath);
ext = ext?ext.slice(1) : 'unknown';
var contentType = MIME_TYPE[ext] || "text/plain";
fs.readFile(filePath,function(err,data){
if(err){
res.end("500服务器内部错误!");
}else{
res.writeHead(200,{'content-type':contentType});
res.end(data.toString());
}
});
//fs.readfile
}
})//path.exists}server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");
function send404(res){
res.end("404【node和express分别实现静态文件服务器】file not found
")
}
使用express框架:
var express = require("express");
var app = express();
app.use("/",express.static(__dirname + "/public"));
app.listen(3000);
推荐阅读
- 携程实习篇|Node.js之process进程
- node中package.json和package-lock.json文件的作用
- sequlize统一格式化时间
- egg 如何接收xml数据
- Node.js在WebStorm中调试
- node npm 设置全局仓库路径
- node require 导入模块解析 加载规则和加载机制
- node|node.js学习笔记-模块module
- window node配置安装的全局模块所在的路径cache的路径
- node|node.js express性能优化