Nodejs combined with MongoDB
Var http = require ("http")
Mongo = require ("mongodb")
Events = require ("events")
Http.createServer (function (req, res) {
Var products_emitter = new events.EventEmitter ()
/ / create a link to the northwind database. Equivalent to use northwind
Db = new mongo.Db ("northwind", new mongo.Server ('localhost', 27017, {}), {})
Var listener = function (products) {
Var html = [], len = products.length
Html.push ('')
Html.push ('')
Html.push ('')
Html.push ('Nodejs')
Html.push ('')
Html.push ('')
If (len > 0) {
Html.push ('')
For (var I = 0; I < len; iTunes +) {
Html.push (''+ products [I] .name +'')
}
Html.push ('')
}
Html.push ('')
Html.push ('')
Res.writeHead (200, "Content-Type: text/html")
Res.write (html.join ('))
Res.end ()
ClearTimeout (timeout)
}
Products_emitter.on ('products', listener)
Var timeout = setTimeout (function () {
Products_emitter.emit ('products', [])
Products_emitter.removeListener ('products', listener)
}, 10000)
Db.open (function () {
/ / Open the table named products
Db.collection ("products", function (err, collection) {
/ / select * from products is equivalent to db.products.find ()
Collection.find (function (err, cursor) {
Cursor.toArray (function (err, items) {
Products_emitter.emit ('products', items)
});
});
});
});
}) .customers (8000)
Console.log ("Started")