IT技术博客大学习 共学习 共进步

Nodejs和MongoDB初体验

记事本 2011-01-18 22:18:35 浏览 5,762 次

学习了一下Nodejs和MongoDB,写了个示例程序,读取数据库中产品的列表。

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");

建议继续学习

  1. 为什么我们要从 NodeJS 迁移到 Ruby on Rails (阅读 6,201)
  2. JavaScript,只有你想不到 (阅读 6,163)
  3. MongoDB与内存 (阅读 6,000)
  4. 使用socket.io和node.js搭建websocket应用 (阅读 5,140)
  5. 白话MongoDB(一) (阅读 4,662)
  6. 我为什么选择MongoDB (阅读 4,660)
  7. nodejs教程:配置nodejs.exe的windows目录结构 (阅读 4,540)
  8. MySQL和MongoDB设计实例对比 (阅读 4,522)
  9. 也来玩玩MongoDB (阅读 4,484)
  10. node.js调研与服务性能测试 (阅读 4,462)