Created
July 26, 2011 06:37
-
-
Save iwillwen/1106126 to your computer and use it in GitHub Desktop.
A micro blog powered by Node.js with Web.js and JSData.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'); | |
var colls = {}; | |
jsd = exports; | |
function Collection (json) { | |
this.data = json; | |
this.toJSON = function () { | |
return this.data; | |
}; | |
this.findOne = function (opt) { | |
var res = {}; | |
res.self = this.data; | |
res.coll = []; | |
for (var key in opt) { | |
for (var i = 0;i < res.self.length;i++) { | |
if (res.self[i][key] == opt[key]) res.coll.push(res.self[i]); | |
} | |
res.self = res.coll; | |
res.coll = []; | |
} | |
return res.self[0]; | |
}; | |
this.find = function (opt) { | |
var res = {}; | |
res.self = this.data; | |
res.coll = []; | |
for (var key in opt) { | |
for (var i = 0;i < res.self.length;i++) { | |
if (res.self[i][key] == opt[key]) res.coll.push(res.self[i]); | |
} | |
res.self = res.coll; | |
res.coll = []; | |
} | |
return res.self; | |
}; | |
this.insert = function (model) { | |
model._id = Math.round(Math.random() * 10000000000); | |
this.data.push(model); | |
return this; | |
}; | |
this.getCound = function () { | |
return this.data.length; | |
}; | |
} | |
function collParse (sJSON) { | |
var json = JSON.parse(sJSON); | |
coll = colls[Math.round(Math.random() * 100000000)] = new Collection(json); | |
return coll; | |
} | |
jsd.collection = function (collName) { | |
return collParse(fs.readFileSync('./' + collName + '.json').toString()); | |
}; | |
jsd.create = function (collName) { | |
fs.readFile('./' + collName + '.json', function (err, data) { | |
if (err) { | |
fs.writeFile(collName + '.json', '[]'); | |
return this; | |
} else { | |
console.log('The collection`s file name was existed'); | |
return this; | |
} | |
}); | |
}; | |
jsd.remove = function (collName) { | |
fs.unlink('./' + collName + '.json'); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"type" : "title", | |
"content" : "Nodebook" | |
}, | |
{ | |
"type" : "url", | |
"content" : "http://www.nodebook.org" | |
}, | |
{ | |
"type" : "author", | |
"content" : "Will Wen Gunn" | |
} | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Modules | |
var web = require('webjs'), | |
jsd = require('jsdata'); | |
jsd.create('nodebook') | |
.create('nodebook-meta') | |
.create('nodebook-comment'); | |
var posts = jsd.collection('nodebook'), | |
metas = jsd.collection('nodebook-meta'), | |
comments = jsd.collection('nodebook-comments'); | |
var urls = { | |
'^post/([a-zA-Z0-9])' : 'post.html', | |
'^([a-zA-Z0-9])' : 'page.html' | |
}, | |
gets = { | |
'getpost' : function (req, res, qs) { | |
res.send(db.findOne(qs)); | |
}, | |
'getmeta' : function (req, res, qs) { | |
res.send(metas.findOne(qs)); | |
}, | |
'getcomments' : function (req, res, qs) { | |
var coms = comments.find({pid:qs.pid}); | |
res.sendJSON(coms); | |
} | |
}, | |
posts = { | |
'post' : function (req, res, qs) { | |
posts.insert(qs); | |
res.send(posts.findOne(qs)._id); | |
}, | |
'comment' : function (req, res, qs) { | |
comments.insert(qs); | |
res.send(comments.findOne(qs)._id); | |
} | |
}; | |
web.run(urls, 80) | |
.get(gets) | |
.post(posts); | |
console.log('enjoy!') |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Modules | |
var http = require("http"), | |
fs = require("fs"), | |
sys = require("sys"), | |
url = require("url"), | |
qs = require("querystring"), | |
net = require("net"), | |
events = require("events"); | |
//Metas | |
var web = exports, | |
urlHandlers = {}, | |
getHandlers = {}, | |
postHandlers = {}, | |
erorrHandlers = {}, | |
blockMimes = {}; | |
web.version = '0.1.4'; | |
web.mimes = { "3gp" : "video/3gpp", | |
"a" : "application/octet-stream", | |
"ai" : "application/postscript", | |
"aif" : "audio/x-aiff", | |
"aiff" : "audio/x-aiff", | |
"asc" : "application/pgp-signature", | |
"asf" : "video/x-ms-asf", | |
"asm" : "text/x-asm", | |
"asx" : "video/x-ms-asf", | |
"atom" : "application/atom+xml", | |
"au" : "audio/basic", | |
"avi" : "video/x-msvideo", | |
"bat" : "application/x-msdownload", | |
"bin" : "application/octet-stream", | |
"bmp" : "image/bmp", | |
"bz2" : "application/x-bzip2", | |
"c" : "text/x-c", | |
"cab" : "application/vnd.ms-cab-compressed", | |
"cc" : "text/x-c", | |
"chm" : "application/vnd.ms-htmlhelp", | |
"class" : "application/octet-stream", | |
"com" : "application/x-msdownload", | |
"conf" : "text/plain", | |
"cpp" : "text/x-c", | |
"crt" : "application/x-x509-ca-cert", | |
"css" : "text/css", | |
"csv" : "text/csv", | |
"cxx" : "text/x-c", | |
"deb" : "application/x-debian-package", | |
"der" : "application/x-x509-ca-cert", | |
"diff" : "text/x-diff", | |
"djv" : "image/vnd.djvu", | |
"djvu" : "image/vnd.djvu", | |
"dll" : "application/x-msdownload", | |
"dmg" : "application/octet-stream", | |
"doc" : "application/msword", | |
"dot" : "application/msword", | |
"dtd" : "application/xml-dtd", | |
"dvi" : "application/x-dvi", | |
"ear" : "application/java-archive", | |
"eml" : "message/rfc822", | |
"eps" : "application/postscript", | |
"exe" : "application/x-msdownload", | |
"f" : "text/x-fortran", | |
"f77" : "text/x-fortran", | |
"f90" : "text/x-fortran", | |
"flv" : "video/x-flv", | |
"for" : "text/x-fortran", | |
"gem" : "application/octet-stream", | |
"gemspec" : "text/x-script.ruby", | |
"gif" : "image/gif", | |
"gz" : "application/x-gzip", | |
"h" : "text/x-c", | |
"hh" : "text/x-c", | |
"htm" : "text/html", | |
"html" : "text/html", | |
"ico" : "image/vnd.microsoft.icon", | |
"ics" : "text/calendar", | |
"ifb" : "text/calendar", | |
"iso" : "application/octet-stream", | |
"jar" : "application/java-archive", | |
"java" : "text/x-java-source", | |
"jnlp" : "application/x-java-jnlp-file", | |
"jpeg" : "image/jpeg", | |
"jpg" : "image/jpeg", | |
"js" : "application/javascript", | |
"json" : "application/json", | |
"log" : "text/plain", | |
"m3u" : "audio/x-mpegurl", | |
"m4v" : "video/mp4", | |
"man" : "text/troff", | |
"mathml" : "application/mathml+xml", | |
"mbox" : "application/mbox", | |
"mdoc" : "text/troff", | |
"me" : "text/troff", | |
"mid" : "audio/midi", | |
"midi" : "audio/midi", | |
"mime" : "message/rfc822", | |
"mml" : "application/mathml+xml", | |
"mng" : "video/x-mng", | |
"mov" : "video/quicktime", | |
"mp3" : "audio/mpeg", | |
"mp4" : "video/mp4", | |
"mp4v" : "video/mp4", | |
"mpeg" : "video/mpeg", | |
"mpg" : "video/mpeg", | |
"ogv" : "video/ogv", | |
"webm" : "video/webm", | |
"ms" : "text/troff", | |
"msi" : "application/x-msdownload", | |
"odp" : "application/vnd.oasis.opendocument.presentation", | |
"ods" : "application/vnd.oasis.opendocument.spreadsheet", | |
"odt" : "application/vnd.oasis.opendocument.text", | |
"ogg" : "application/ogg", | |
"p" : "text/x-pascal", | |
"pas" : "text/x-pascal", | |
"pbm" : "image/x-portable-bitmap", | |
"pdf" : "application/pdf", | |
"pem" : "application/x-x509-ca-cert", | |
"pgm" : "image/x-portable-graymap", | |
"pgp" : "application/pgp-encrypted", | |
"pkg" : "application/octet-stream", | |
"pl" : "text/x-script.perl", | |
"pm" : "text/x-script.perl-module", | |
"png" : "image/png", | |
"pnm" : "image/x-portable-anymap", | |
"ppm" : "image/x-portable-pixmap", | |
"pps" : "application/vnd.ms-powerpoint", | |
"ppt" : "application/vnd.ms-powerpoint", | |
"ps" : "application/postscript", | |
"psd" : "image/vnd.adobe.photoshop", | |
"py" : "text/x-script.python", | |
"qt" : "video/quicktime", | |
"ra" : "audio/x-pn-realaudio", | |
"rake" : "text/x-script.ruby", | |
"ram" : "audio/x-pn-realaudio", | |
"rar" : "application/x-rar-compressed", | |
"rb" : "text/x-script.ruby", | |
"rdf" : "application/rdf+xml", | |
"roff" : "text/troff", | |
"rpm" : "application/x-redhat-package-manager", | |
"rss" : "application/rss+xml", | |
"rtf" : "application/rtf", | |
"ru" : "text/x-script.ruby", | |
"s" : "text/x-asm", | |
"sgm" : "text/sgml", | |
"sgml" : "text/sgml", | |
"sh" : "application/x-sh", | |
"sig" : "application/pgp-signature", | |
"snd" : "audio/basic", | |
"so" : "application/octet-stream", | |
"svg" : "image/svg+xml", | |
"svgz" : "image/svg+xml", | |
"swf" : "application/x-shockwave-flash", | |
"t" : "text/troff", | |
"tar" : "application/x-tar", | |
"tbz" : "application/x-bzip-compressed-tar", | |
"tcl" : "application/x-tcl", | |
"tex" : "application/x-tex", | |
"texi" : "application/x-texinfo", | |
"texinfo" : "application/x-texinfo", | |
"text" : "text/plain", | |
"tif" : "image/tiff", | |
"tiff" : "image/tiff", | |
"torrent" : "application/x-bittorrent", | |
"tr" : "text/troff", | |
"txt" : "text/plain", | |
"vcf" : "text/x-vcard", | |
"vcs" : "text/x-vcalendar", | |
"vrml" : "model/vrml", | |
"war" : "application/java-archive", | |
"wav" : "audio/x-wav", | |
"wma" : "audio/x-ms-wma", | |
"wmv" : "video/x-ms-wmv", | |
"wmx" : "video/x-ms-wmx", | |
"webp" : "image/webp", | |
"wrl" : "model/vrml", | |
"wsdl" : "application/wsdl+xml", | |
"xbm" : "image/x-xbitmap", | |
"xhtml" : "application/xhtml+xml", | |
"xls" : "application/vnd.ms-excel", | |
"xml" : "application/xml", | |
"xpm" : "image/x-xpixmap", | |
"xsl" : "application/xml", | |
"xslt" : "application/xslt+xml", | |
"yaml" : "text/yaml", | |
"yml" : "text/yaml", | |
"zip" : "application/zip" | |
}, | |
web.metas = {}, | |
web.servers = []; | |
//Foundation Server | |
var server; | |
function createHttpServer() { | |
var content; | |
server = http.createServer(function (req, res) { | |
var path = url.parse(req.url).pathname.substring(1); | |
//Response | |
res.send = function (data, alive) { | |
this.writeHead(200, {'Content-Type' : "text/html"}); | |
this.write(data); | |
if (alive) { | |
return this; | |
} else { | |
this.end(); | |
return this; | |
} | |
}; | |
res.sendFile = function (fileName) { | |
var format = fileName.split('.'); | |
fs.readFile("./" + fileName, function (err, data) { | |
if (err) return send404(res); | |
this.charset = web.mimes[format[format.length - 1]]; | |
res.writeHead(200, {'Content-Type' : this.charset}); | |
res.write(data); | |
res.end(); | |
}); | |
} | |
res.sendJSON = function (data) { | |
switch (typeof data) { | |
case "string": | |
this.charset = "application/json"; | |
res.writeHead(200, {'Content-Type' : this.charset}); | |
res.write(data); | |
res.end(); | |
break; | |
case "array": | |
case "object": | |
var sJSON = JSON.stringify(data); | |
this.charset = "application/json"; | |
res.writeHead(200, {'Content-Type' : this.charset}); | |
res.write(sJSON); | |
res.end(); | |
break; | |
} | |
} | |
res.cookie = function (name, val, options) { | |
options = options || {}; | |
if ('maxAge' in options) options.expires = new Date(Date.now() + options.maxAge); | |
if (undefined === options.path) options.path = this.app.set('home'); | |
var cookie = utils.serializeCookie(name, val, options); | |
this.header('Set-Cookie', cookie); | |
return this; | |
}; | |
res.clearCookie = function (name, options) { | |
var opts = { expires: new Date(1) }; | |
return this.cookie(name, '', options | |
? utils.merge(options, opts) | |
: opts); | |
}; | |
//Request | |
req.addListener('data', function(chunk) { | |
content += chunk; | |
}); | |
req.type = function(type) { | |
var contentType = this.headers['content-type']; | |
if (!contentType) return; | |
if (!~type.indexOf('/')) type = web.mimes[type]; | |
if (~type.indexOf('*')) { | |
type = type.split('/') | |
contentType = contentType.split('/'); | |
if ('*' == type[0] && type[1] == contentType[1]) return true; | |
if ('*' == type[1] && type[0] == contentType[0]) return true; | |
} | |
return !! ~contentType.indexOf(type); | |
}; | |
req.header = function (sHeader) { | |
if (this.headers[sHeader]) { | |
return this.headers[sHeader]; | |
} else { | |
return undefined; | |
} | |
} | |
switch (req.method) { | |
case "GET": | |
getHandler(req, res, path); | |
break; | |
case "POST": | |
postHandler(req, res, path); | |
break; | |
} | |
}); | |
return server; | |
} | |
//404 page | |
var page404 = "Page not found.", | |
send404 = function (res) { | |
res.send(page404); | |
}; | |
//HTTP handler | |
var getHandler = function (req, res, getpath) { | |
switch (getpath) { | |
case "": | |
if ("/" in urlHandlers) { | |
res.sendFile(urlHandlers["/"]); | |
} else if ("/" in getHandlers) { | |
getHandlers["/"](req, res); | |
} else { | |
res.sendFile("index.html"); | |
} | |
break; | |
case "favicon.ico": | |
res.sendFile("favicon.ico"); | |
break; | |
default: | |
for (var key in getHandlers) { | |
var uhReg = new RegExp(key, "i"); | |
var querystrings = url.parse(req.url, true).query; | |
if (uhReg.test(getpath)) { | |
try { | |
getHandlers[key](req, res, querystrings); | |
} catch(ex) { | |
if (erorrHandlers.get) { | |
return erorrHandlers.get(req, res); | |
} else { | |
return send404(res); | |
} | |
} | |
} | |
} | |
urlHandler(req, res, getpath); | |
} | |
}, | |
urlHandler = function (req, res, getpath) { | |
var scriptfile; | |
for (var key in urlHandlers) { | |
var uhReg = new RegExp(key, "i"); | |
if (uhReg.test(getpath)) { | |
scriptfile = urlHandlers[key]; | |
break; | |
} | |
} | |
if (/^http/.test(scriptfile)) { | |
res.setHeader('Location', scriptfile); | |
res.writeHead(301, {'Content-Type': 'text/html'}); | |
res.end('<meta http-equiv="refresh" content="5; ' + scriptfile + '" /><p>Redirecting to ' + scriptfile + '</p>'); | |
console.log('Redirected to ' + scriptfile); | |
return; | |
} | |
if (scriptfile !== undefined) { | |
fs.readFile("./" + scriptfile, function (err, data) { | |
if (err) return send404(res); | |
var format = scriptfile.split("."); | |
res.writeHead(200, {'Content-Type': web.mimes[format[format.length -1]]}); | |
res.write(data, 'utf8'); | |
res.end(); | |
}); | |
} else { | |
fileHandler(req, res, getpath); | |
} | |
}, | |
postHandler = function (req, res, postpath) { | |
var request = {}; | |
content = content.substring(15); | |
request = qs.parse(content); | |
for (var key in postHandlers) { | |
var uhReg = new RegExp(key, "i"); | |
if (uhReg.test(postpath)) { | |
try { | |
postHandlers[key](req, res, request); | |
} catch(ex) { | |
if (erorrHandlers.post) { | |
return erorrHandlers.post(req, res); | |
} else { | |
return send404(res); | |
} | |
} | |
} | |
} | |
}, | |
fileHandler = function (req, res, getpath) { | |
var format = getpath.split('.'); | |
if (format[format.length - 1] in blockMimes) { | |
blockMimes[format[format.length - 1]](req, res); | |
} else { | |
res.sendFile(getpath); | |
} | |
}; | |
//Method | |
web.get = function (_gethandlers) { | |
var key; | |
for (key in _gethandlers) { | |
getHandlers[key] = _gethandlers[key]; | |
} | |
return this; | |
}; | |
web.post = function (_posthandlers) { | |
var key; | |
for (key in _posthandlers) { | |
postHandlers[key] = _posthandlers[key]; | |
} | |
return this; | |
}; | |
web.run = function (getpath, port, host, backserver) { | |
if (server == undefined) { | |
server = createHttpServer(); | |
web.servers.push(server); | |
} | |
if (getpath == undefined) { | |
server.listen(80); | |
console.log('Server is running on 127.0.0.1:80'); | |
if (backserver) { | |
return server; | |
} else { | |
return this; | |
} | |
} else { | |
var key; | |
for (key in getpath) { | |
urlHandlers[key] = getpath[key]; | |
} | |
if (port !== undefined) { | |
if (host === undefined) { | |
server.listen(port); | |
} else { | |
server.listen(port, host); | |
} | |
} | |
if (backserver){ | |
return server; | |
} else { | |
return this; | |
} | |
} | |
}; | |
web.set404 = function (path) { | |
fs.readFile("./" + path, function (err, data) { | |
page404 = data; | |
}); | |
return this; | |
}; | |
web.erorr = function (handlers) { | |
var key; | |
for (key in handlers) { | |
erorrHandlers[key] = handlers[key]; | |
} | |
return this; | |
}; | |
web.noMimes = function (handlers) { | |
var key; | |
for (key in handlers) { | |
blockMimes[key] = handlers[key]; | |
} | |
return this; | |
}; | |
web.meta = function (key, value) { | |
this.metas[key] = value; | |
return this; | |
}; | |
web.reg = function (format, mime) { | |
if (/^./.test(format)) { | |
this.mimes[format.substring(1)] = mime; | |
} else { | |
this.mimes[format] = mime; | |
} | |
return this; | |
}; | |
web.server = server; | |
//TCP Server | |
var sockets = []; | |
web.net = function (port, callback) { | |
var tcpServer = net.createServer(function (socket) { | |
sys.inherits(socket, events.EventEmitter); | |
socket.id = Math.round(Math.random() * 10000000000); | |
socket.on('connect', function () { | |
for (var i = 0; i < socket.listeners('connection').length; i++) { | |
socket.listeners('connection')[i](); | |
} | |
}); | |
socket.on('data', function (data) { | |
for (var i = 0; i < socket.listeners('message').length; i++) { | |
socket.listeners('message')[i](data); | |
} | |
}); | |
socket.on('end', function () { | |
var a = sockets.indexOf(socket); | |
sockets.splice(a, 1); | |
for (var i = 0; i < socket.listeners('disconnect').length; i++) { | |
socket.listeners('disconnect')[i](); | |
} | |
}); | |
socket.send = function (str) { | |
socket.write(str); | |
console.log('send success'); | |
}; | |
socket.broadcast = function (data) { | |
for (var i = 0; i < sockets.length; i++) { | |
if (sockets[i] == socket) continue; | |
sockets[i].write(data); | |
} | |
}; | |
sockets.push(socket); | |
callback(socket); | |
}).listen(port); | |
return tcpServer; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment