项目文件路径:
http.js
这里用到两个JS文件,http.js和mime.js
http.js :创建一个httpServer并监听3000端口
var PORT = 3000;
var http = require(‘http‘);
var url = require(‘url‘);
var fs = require(‘fs‘); //fs模块是用于读取文件
var mime = require(‘./mime‘).types;
var path = require(‘path‘);
var server = http.createServer(function(request, response) {
var pathname = url.parse(request.url).pathname;
var realPath = path.join("frontEnd", pathname);//webapp就是放置一些静态资源文件的目录,这个可以根据自己的项目需求作修改
//console.log(realPath);
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : ‘unknown‘;
fs.exists(realPath, function(exists) {
if (!exists) {
response.writeHead(404, {
‘Content-Type‘: ‘text/plain‘
});
response.write("This request URL " + pathname + " was not found on this server.");
response.end();
} else {
fs.readFile(realPath, "binary", function(err, file) {
if (err) {
response.writeHead(500, {
‘Content-Type‘: ‘text/plain‘
});
response.end(err);
} else {
var contentType = mime[ext] || "text/plain";
response.writeHead(200, {
‘Content-Type‘: contentType
});
response.write(file, "binary");
response.end();
}
});
}
});
});
server.listen(PORT);
console.log("Server runing at port: " + PORT + ".");
使用mime模块设定文件类型
什么是mime?
MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型。是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。
上面http.js中引入了mime.js,下面就定义一下类型
exports.types = {
"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",
"woff": "application/x-woff",
"woff2": "application/x-woff2",
"tff": "application/x-font-truetype",
"otf": "application/x-font-opentype",
"eot": "application/vnd.ms-fontobject"
};
然后打开命令行,输入命令:
node http
运行成功如图所示