【JavaScript】Node.js服务器端程序代码改进(识别url中的参数)

时间:2022-03-24 10:00:36

说明:

以下这段Node.js服务器端代码是在rabby给出的代码基础上改进的。

(参见http://cnodejs.org/topic/4f3b52eab43c3c846a04ba22

本次改进主要解决了当url包含参数时,页面不能正确显示的问题。

修改方案就是加了一个字串的判断,若有参数就CUT掉参数之后的内容。 

 

var http = require('http');
var fs = require('fs');
var path = require('path');
var util = require('util');

http.createServer(function (request, response) {
console.log('request starting...');

var filePath = '.' + request.url;
if (filePath == './')
filePath = './RC-KMS/RC-KMS.html'
else
filePath = './RC-KMS/' + filePath;

if (filePath.indexOf('?')>0)
var fileName = filePath.substr(0,filePath.indexOf('?'));
else
var fileName = filePath;
console.log(fileName);

var extname = path.extname(fileName);
var contentType = 'text/html';
var ifbinary = false;
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.gif':
contentType = 'image/gif';
ifbinary = true;
break;
case '.png':
contentType = 'image/png';
ifbinary = true;
break;
case '.jpg':
contentType = 'image/jpeg';
ifbinary = true;
break;
}

path.exists(fileName, function(exists) {

if (exists) {
if (ifbinary) {
fs.stat(fileName, function(error, stat) {
var rs;
response.writeHead(200,{ 'Content-Type': contentType, 'Content-Length' : stat.size });
rs = fs.createReadStream(fileName);
util.pump(rs, response, function(err) {
if(err) {
throw err;
}
});
});
}
else {
fs.readFile(fileName, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');