chat/lib/web.js
2020-10-24 11:44:53 +08:00

124 lines
3.4 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

var fs = require('fs');
var path = require('path');
const querystring = require('querystring');
var chat = require('./chat');
var routes = {};
var route = {
on: function (url, handler) {
routes[url] = handler;
},
endRequest: (response, header, data) => {
if (data) {
header['Content-Type'] = 'text/html; charset=UTF-8';
if (typeof (data) != 'string') {
data = JSON.stringify(data)
header['Access-Control-Allow-Origin'] = '*';
header['Content-Type'] = 'application/json; charset=UTF-8';
}
} else {
data = '';
}
response.writeHead(200, header);
response.end(data);
},
process: function (request, response) {
var header = {
'Content-Type': 'text/html; charset=UTF-8',
'Server': 'chat-server'
};
var requestUrl = request.url.toLowerCase();
if (typeof (routes[requestUrl]) == "function") {
var data = routes[requestUrl](request, response);
let isCallback = data instanceof Promise;
if (isCallback) {
data.then((resp) => {
route.endRequest(response, header, resp);
})
} else {
route.endRequest(response, header, data);
}
} else {
response.writeHead(200, header);
response.end('chat-server is running!');
}
}
};
route.on('/online', function () {
return chat.getUserList();
});
route.on('/reg', function (req, response) {
return new Promise((res, rej) => {
var data = '';
req.on('data', function (chunk) {
data += chunk;
});
req.on('end', function () {
//1.对url进行解码url会对中文进行编码
console.log(data);
data = JSON.parse(decodeURI(data));
console.log(data);
res({
code: 1,
message: '错误的数据',
data: data
});
});
})
});
var coreProcess = function (request, response) {
var requestUrl = request.url.toLowerCase();
var realPath = path.join('static', 'chat.html');
if (requestUrl == '/chat_client.js') {
realPath = path.join('static', 'chat_client.js');
}
console.log(realPath);
fs.exists(realPath, function (exists) {
fs.stat(realPath, function (err, stat) {
var lastModified = stat.mtime.toUTCString();
var ifModifiedSince = "If-Modified-Since".toLowerCase();
response.setHeader("Last-Modified", lastModified);
var expires = new Date();
var maxAge = 60 * 60 * 24 * 365;
expires.setTime(expires.getTime() + maxAge * 1000);
response.setHeader("Expires", expires.toUTCString());
response.setHeader("Cache-Control", "max-age=" + maxAge);
if (lastModified == request.headers[ifModifiedSince]) {
response.writeHead(304, "Not Modified");
response.end();
} else {
var raw = fs.createReadStream(realPath);
response.writeHead(200, "Ok");
raw.pipe(response);
}
});
});
};
route.on('/', coreProcess);
route.on('/chat_client.js', coreProcess);
exports = module.exports = {
handler: route.process
};