首页 > Web开发 > 详细

Node.js搭建本地服务,读取css/js/img/html等各种格式文件

时间:2020-12-01 18:06:44      阅读:28      评论:0      收藏:0      [点我收藏+]

项目文件路径:

技术分享图片

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等各种格式文件

原文:https://www.cnblogs.com/midnight-visitor/p/14069321.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!