IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

Nodejs和MongoDB初体验

记事本 2011-01-18 22:18:35 累计浏览 5,867 次
本机暂存

学习了一下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. 等了十年的 Go 链式管道,终于来了:seq 让你像写 Scala 一样写 Go (2026-06-25 18:38:18)
  2. Go 实验特性详解 (2026-06-21 10:05:27)
  3. amd64 微架构级别对 Go 程序性能提升多少? (2026-06-21 09:38:49)

查看更多 后端 文章 →

建议继续学习

  1. JQuery实现Excel表格呈现 (累计阅读 48,349)
  2. 深入理解Javascript之执行上下文(Execution Context) (累计阅读 18,403)
  3. 从输入 URL 到页面加载完成的过程中都发生了什么事情? (累计阅读 15,932)
  4. 图片动态局部毛玻璃模糊效果的实现 (累计阅读 14,848)
  5. 天朝第二代身份证号码的验证机制 (累计阅读 14,761)
  6. HTML 5 的data-* 自定义属性 (累计阅读 14,349)
  7. 分享一个JQUERY颜色选择插件 (累计阅读 14,223)
  8. 什么是全栈工程师? (累计阅读 14,036)
  9. 快速排序(Quicksort)的Javascript实现 (累计阅读 11,735)
  10. 7 天打造前端性能监控系统 (累计阅读 11,187)