Rumah > Soal Jawab > teks badan
初学nodeJS,在使用nodejs构建静态文件服务器的时候,遇到下面问题。
用户请求index.html时,我使用fs.readFile
读取index.html并将data返回,代码如下:
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{
fs.readFile(filePath,function(err,data){
if(err){
res.end("<h1>500</h1>服务器内部错误!");
}else{
res.writeHead(200,{'content-type':'text/html'});
res.end(data.toString());
}
});//fs.readfile
}
})//path.exists
}//serverStatic
那么问题来了,如果我的HTML页面引用了外部的css或者js,那么这些外部文件不会被加载···
这个问题怎么解决?
尝试:
index源码:
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<link href="css/index.css">
</head>
<body>
<a href="flexbox.html">看看伸缩盒?</a>
</body>
</html>
css:
body{background-color:red;}
app.js:
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("<h1>500</h1>服务器内部错误!");
}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("<h1>404</h1><p>file not found</p>")
}
chrome查看网络:
我的文件结构
PHP中文网2017-04-10 16:56:48
下面是一个静态文件访问的模块
/**
* 引入模块
* @type {[type]}
*/
var fs =require("fs");
var mime =require("mime");
var path =require("path");
/*******************************************************************************************/
/**
* [Send 创建发送响应对象]
*/
function Send(){};
Send.prototype.cache={};//设置缓存变量,因为缓存变量比读取文件要快
/**
* 错误404页面
* @param {[type]} res [description]
* @return {[type]} [description]
*/
Send.prototype.err404 = function(res){
res.writeHead(404,{"Content-Type":"text/plain"});
res.write("404 Not Fount !");
res.end();
};
/**
* 正确访问页面
* @param {[type]} res [description]
* @param {[type]} fileName [description]
* @param {[type]} fileContent [description]
* @return {[type]} [description]
*/
Send.prototype.sendFile = function(res,fileName,fileContent){
res.writeHead(200,{"Content-Type":mime.lookup(path.basename(fileName))});
res.end(fileContent);
};
/**
* 发送静态页面方法
* @param {[type]} res [description]
* @param {[type]} absPath [description]
* @return {[type]} [description]
*/
Send.prototype.serveStatic = function(res,absPath){
var _this=this;
if(this.cache[absPath]){
this.sendFile(res,absPath,this.cache[absPath]);
}else{
fs.exists(absPath,function(exists){
if(exists){
fs.readFile(absPath,function(err,data){
if(err){
_this.err404(res);
}else{
_this.sendFile(res,absPath,data);
}
})
}else{
_this.err404(res);
}
})
}
};
Send.prototype.staticDirectory=function(req,url){
var filePath=false;
if(new RegExp("^/"+url+"/.*").test(req.url)){
filePath=url+req.url;
}
var absPath="./"+filePath;
return absPath;
}
/*******************************************************************************************/
module.exports=Send;
调用方法
/**
* 引入HTTP组建,创建HTTP服务器的核心组件
* @type {[type]}
*/
var http=require("http");
var sio=require("socket.io");
/**
* 引入自定义组件,
* @type {[type]}
*/
var staticService=require("./modules/staticService");
/*************************************************/
/**
* 创建http服务
* @param {[type]} req [description]
* @param {[type]} res){ var filePath [description]
* @return {[type]} [description]
*/
var server = http.createServer(function(req,res){
var send=new staticService();
var absPath=send.staticDirectory(req,"public")
send.serveStatic(res,absPath);
});
server.listen(8200,function(){
console.log("Http server create success on : localhost:8200");
})
PHP中文网2017-04-10 16:56:48
fs.exists(filePath,function(err)
如果文件存在,回掉函数的第1个参数为true
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 = "CSSTest.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("<h1>500</h1>服务器内部错误!");
}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 + ".");
高洛峰2017-04-10 16:56:48
前几天刚有人问这个问题的
http://segmentfault.com/q/1010000004317668?_ea=567469
利用nodejs搭建静态文件服务器