Chris Cowan
Twitter: @uhduh
Github: ccowan
console.log('Hello World');
node helloworld.js
Hello World
var http = require('http');
var server = http.createServer(function (req, res) {
res.writeHead(200);
res.end('Hello World');
});
server.listen(4000);
// Get Users - 20ms
$query = 'SELECT * FROM users WHERE id = ?';
$users = query($query, array($_GET['id']));
print_r($users);
// Get Activities - 130ms
$query = 'SELECT * FROM activities WHERE user_id = ? ORDER BY TIMESTAMP LIMIT 50';
$activities = query($query, array($_GET['id']));
print_r($activities);
// Get Leader Board - 120ms
$query = 'SELECT count(points),user_id FROM activities GROUP BY user_id LIMIT 50';
$leader_board = query($query);
print_r($leader_board);
// Get Users - 20ms
var query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [req.query.id], function (err, users) {
console.log(users);
});
// Get Activities - 130ms
query = 'SELECT * FROM activities WHERE user_id = ? ORDER BY TIMESTAMP LIMIT 50';
db.query(query, [req.query.id], function (err, activities) {
console.log(activities);
});
// Get Leader Board - 120ms
query = 'SELECT count(points),user_id FROM activities GROUP BY user_id LIMIT 50';
db.query(query, function (err, leader_board) {
console.log(leader_board);
});
awesomeFunction(args, function (err, data) {
if (err) {
// Handle Error
}
// Do something awesome with the data
});
db.query(userQuery, [id], function (err, userResults) {
db.query(activityQuery, [id], function (err, activityResults) {
db.query(leaderBoardQuery, function (err, leaderBoardResults) {
// I HATE MY LIFE!
});
});
});
var async = require('async');
var db = require(’db');
function getUser (callback) {
var query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId], callback);
}
function getActivities (callback) {
var query = 'SELECT * FROM activities ORDER BY timestamp LIMIT 50';
db.query(query, callback);
}
function getLeaderBoard (callback) {
var query = 'SELECT count(points) as total, user_id FROM activities LIMIT 50';
db.query(query, callback);
}
var tasks = [getUser, getActivities, getLeaderBoard];
async.parallel(tasks, function (err, results) {
var user = results[0][0];
var activities = results[1];
var leaderBoard = results[2];
});
npm install <module>
npm find <module>
npm list
var currentCount = 0;
module.exports.incr = function () {
return ++currentCount;
};
var counter = require('./counter');
counter.incr();
var count = counter.inrc();
Keep this in mind... modules are loaded once and cached. So when you load the module a second time in your app, require just returns the cached module object. This lets you do interesting things...
"dependencies": {
"my-module": "https://github.com/my-name/my-module/tarball/master"
}
Link the module by hand to your projects node_modules directory