技术头条 - 一个快速在微博传播文章的方式     搜索本站
您现在的位置首页 --> JavaScript --> Nodejs和MongoDB初体验

Nodejs和MongoDB初体验

浏览:4962次  出处信息

学习了一下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    (阅读:5394)
  2. MongoDB与内存    (阅读:5231)
  3. JavaScript,只有你想不到    (阅读:4947)
  4. 使用socket.io和node.js搭建websocket应用    (阅读:4239)
  5. 我为什么选择MongoDB    (阅读:3813)
  6. node.js调研与服务性能测试    (阅读:3605)
  7. 白话MongoDB(一)    (阅读:3565)
  8. 基于express+socket.io的nodejs聊天室    (阅读:3522)
  9. MySQL和MongoDB设计实例对比    (阅读:3503)
  10. nodejs教程:配置nodejs.exe的windows目录结构    (阅读:3420)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
© 2009 - 2024 by blogread.cn 微博:@IT技术博客大学习

京ICP备15002552号-1