Skip to content

Instantly share code, notes, and snippets.

@stupend
Created August 5, 2011 06:52
Show Gist options
  • Save stupend/1127048 to your computer and use it in GitHub Desktop.
Save stupend/1127048 to your computer and use it in GitHub Desktop.
example for mongojs+express+mysql
var express = require('express');
var app = module.exports = express.createServer();
app.register('.html', require('jade'));
// Configuration
app.configure(function () {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function () {
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
app.configure('production', function () {
app.use(express.errorHandler());
});
var sys = require('sys');
var Client = require('mysql').Client;
var client = new Client();
client.database = 'db';
client.host = "localhost";
client.user = 'root';
client.password = '';
client.connect(function (error, results) {
if (error) {
console.log('Connection Error: ' + error.message);
return;
}
console.log('Connected to MySQL');
});
var ids = new Array();
client.query('select id,level from u_log order by create_time desc limit 10000', function (error, results, fields) {
for (var i = 0; i < results.length; i++) {
ids.push(results[i]['id'])
}
console.log("Load " + ids.length + " user ids.")
client.end();
});
Array.prototype.has = function (v) {
for (i = 0; i < this.length; i++) {
if (this[i] == v) return i;
}
return false;
}
fetchFriendIds = function () {
if (ids.length <= 100) {
if (ids.length <= 12) {
return ids;
}
return ids.slice(0, 12);
}
var i = 0;
var r = [];
while (i < 12) {
var n = Math.floor(Math.random() * (ids.length));
console.log(n)
if (!r.has(n)) {
r.push(n)
i++;
}
}
return r;
}
var db = require('mongojs').connect('192.168.1.112/test', ['user_info']);
var cache = {};
app.get('/', function (req, res) {
// 获取推荐好友列表
t = fetchFriendIds();
var us = [];
var fids = [];
//检查缓存
for (var i = 0; i < t.length; i++) {
var uid = t[i];
if (cache[uid] != null) {
us[uid] = cache[uid];
} else {
fids.push(uid);
}
}
db.user_info.find({
"a": {
"$in": fids
}
}).forEach(function (a, u) {
if (u != null) {
var r = {};
var id = u['a'];
r['id'] = id;
r['pic'] = u['d'];
r['name'] = u['c'];
cache[id] = r;
us.push(r);
}
if (a == null && u == null) {
// 循环结尾,输出到web
res.render('index', {
users: us
});
}
});
});
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment