好吧,对于那些像我一样不熟悉的人来说,这是一种不使用 Express 来显示最常见文件类型的方法。
var file_path = "";
var mimes = {
'css': 'text/css',
'js': 'text/javascript',
'htm': 'text/html',
'html': 'text/html',
'png': 'image/png',
'jpg': 'image/jpg',
'jpeg': 'image/jpeg'
};
// parses the url request for a file and pulls the pathname
var url_request = url.parse(request.url).pathname;
// finds the placement of '.' to determine the extension
var tmp = url_request.lastIndexOf(".");
// determines the extension by uing .substring that takes everything after '.'
var extension = url_request.substring((tmp + 1));
//set path of static pages
if (extension === 'css' || extension === 'js' || extension === 'htm' || extension === 'html' || extension === 'png' || extension === 'jpg' || extension === 'jpeg'){
file_path = url_request.replace("/", "");
}
//load needed pages and static files
fs.readFile(file_path, function (error, data){
if(error){
response.writeHeader(500, {"Content-Type": "text/html"});
response.write("<h1>FS READ FILE ERROR: Internal Server Error!</h1>");
}
else{
response.writeHeader(200, {"Content-Type": mimes[extension]});
response.write(data);
}
response.end();
});
我很想知道不使用 Express 的更简洁的方法。