您好,登錄后才能下訂單哦!
var http = require("http"),
mongo = require("mongodb"),
events = require("events");
http.createServer(function(req, res) {
var products_emitter = new events.EventEmitter(),
// 創建到northwind數據庫的鏈接。相當于use northwind
db = new mongo.Db("northwind", new mongo.Server('localhost', 27017, {}), {});
var listener = function(products) {
var html = [], len = products.length;
html.push('<!DOCTYPE html>');
html.push('<html>');
html.push('<head>');
html.push('<title>Nodejs</title>');
html.push('</head>');
html.push('<body>');
if(len > 0) {
html.push('<ul>');
for(var i = 0; i < len; i++) {
html.push('<li>' + products[i].name + '</li>');
}
html.push('</ul>');
}
html.push('</body>');
html.push('</html>');
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() {
// 打開名為products的表
db.collection("products", function(err, collection) {
// select * from products 相當于db.products.find()
collection.find(function(err, cursor) {
cursor.toArray(function(err, items) {
products_emitter.emit('products', items);
});
});
});
});
}).listen(8000);
console.log("Started");
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。