Node.js搭建本地服务,读取css/js/img/html等各种格式文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Node.js搭建本地服务,读取css/js/img/html等各种格式文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2285字,纯文字阅读大概需要4分钟。
内容图文
![Node.js搭建本地服务,读取css/js/img/html等各种格式文件](/upload/InfoBanner/zyjiaocheng/620/7034e6a9607d4e38acc6d39e36584fa4.jpg)
项目文件路径:
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
运行成功如图所示
然后浏览器输入http://127.0.0.1:3000/index.html 就可以访问拉
内容总结
以上是互联网集市为您收集整理的Node.js搭建本地服务,读取css/js/img/html等各种格式文件全部内容,希望文章能够帮你解决Node.js搭建本地服务,读取css/js/img/html等各种格式文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。