node.js搭建本地web服务器

2017-06-19阅读(5532)评论(0)牵着狗狗看MM

苏州实时公交查询

以前配置本地一个web服务器,访问一些页面,要么IIS,要么apache,现在有了node.js,随时随地我们都可以搭建一个本地的web服务器。

第一步:下载安装node.js

这里就不去多讲如何安装node.js了,windows下的可以看这篇初识Node.js(WIN7环境下的安装与体验)

项目文件路径:

http.js
这里用到两个JS文件,http.js和mime.js
http.js :创建一个httpServer并监听3000端口

[js]
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("webapp", 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 + ".");

[/js]

使用mime模块设定文件类型

什么是mime?
MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型。是设定某种扩展名的文件用一种应用程序来打开的方式类型,当该扩展名文件被访问的时候,浏览器会自动使用指定应用程序来打开。多用于指定一些客户端自定义的文件名,以及一些媒体文件打开方式。
上面http.js中引入了mime.js,下面就定义一下类型
mime.js

[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"
};

[/js]

然后打开命令行,输入命令:

[js]node http.js
[/js]
运行成功如图所示

然后浏览器输入http://127.0.0.1:3000/index.html 就可以访问拉

赞(2) 打赏
转载请注明来源:Web前端(W3Cways.com) - Web前端学习之路 » node.js搭建本地web服务器
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏