转载自:https://www.cnblogs.com/chris-jia/articles/9885946.html
仅供参考,学习使用。
首先需要安装 node 环境,不要问我为什么,做前端的都知道node。
新建server.js 搭建HTTPServer
代码如下:
var PORT = 8099; //端口
var DIR = 'test'; //用于存放html的目录
var http = require('http');
var url = require('url');
var fs = require('fs');
var mine = require('./mine').types;
var path = require('path');
var server = http.createServer(function(request, response) {
var pathname = url.parse(request.url).pathname;
var realPath = path.join(DIR, pathname);
//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 = mine[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 + '.');
新建mine.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'
};
运行代码:
node server.js
运行结果:
node server.js
Server runing at port: 8099.
为了方便后期使用可以在目录新建 server.bat文件,双击即可运行。
server.bat 文件内容就是执行命令即: node server.js;
忘记说了,在目录下新建 index.html
请求方式:localhost:8099/index.html
over ~_~ ~~