備忘録などに使えるしどうせ見る人もそんなにいないであろう(笑)と思ったので、
これからは小さいネタも載せて更新頻度の向上も目指したいと思ってます(^_^;)
さて、今回はひょんなことからWebアプリを作らないといけなくなったわけなのですが、
その際にnode.jsを使わせて頂いているわけです。
そこでまぁnpmを使って他のパッケージを利用するのもいいのですが、
今回はJsのクラスで勉強がてら(というか興味)に実装しようと考えたわけです。
まぁこのwebアプリ自体公にするものではなさそうなので大丈夫かなと(おい)
var http = require('http');
var fs = require('fs');
var server = http.createServer();
server.on('request', getJs);
console.log('Server running ...');
var Link_creator = function(source,linkname,type){
this.source = source;
this.linkname = linkname;
this.type = type;
}
Link_creator.prototype.add = function(url,Res){
console.log("function in");
console.log(url);
console.log("type is "+this.type);
if(this.type == 'html'){
if (this.linkname == url) {
fs.readFile(this.source, 'UTF-8', function (err, data) {
Res.writeHead(200, {'Content-Type': 'text/html'});
Res.write(data);
Res.end();
});
}
return Res;
}else if(this.type == 'js'){
if (this.linkname == url) {
fs.readFile(this.source, 'UTF-8', function (err, data) {
Res.writeHead(200, {'Content-Type': 'application/javascript'});
Res.write(data);
Res.end();
});
}
return Res;
}else if(this.type == 'jpg'){
if (this.linkname == url) {
Res.writeHead(200, {'Content-Type': 'image/jpeg'});
Res.end(fs.readFileSync(this.source, 'binary' ),'binary');
}
return Res;
}else if(this.type == 'gif'){
if (this.linkname == url) {
Res.writeHead(200, {'Content-Type': 'image/gif'});
Res.end(fs.readFileSync(this.source, 'binary' ),'binary');
}
return Res;
}else if(this.type == 'css'){
if (this.linkname == url) {
fs.readFile(this.source, 'UTF-8', function (err, data) {
Res.writeHead(200, {'Content-Type': 'text/css'});
Res.write(data);
Res.end();
});
}
return Res;
}
}
// new Link_creator('ローカルファイルの指定','URIの指定','タイプの指定')
var sites = [new Link_creator('./main.html','/index.html','html')
,new Link_creator('./home.html','/','html')];
function getJs(req, res) {
var url = req.url;
console.log(url);
sites.forEach(function(site){
if(site.linkname == url){
console.log(site.source);
res = site.add(url,res);
}
});
}
server.listen(8080);
とまぁこんな感じになります。
ミソは
new Link_creator('ローカルファイルの指定','URIの指定','タイプの指定')ですね。タイプの指定はクラス内のadd関数をゴニョゴニョしてオリジナルのものを
追加すればいいです。
やっぱりオブジェクト指向便利だなぁ…(しみじみ)

0 件のコメント:
コメントを投稿