Nodejs和MongoDB初体验

本文介绍了一个使用Node.js和MongoDB从数据库读取产品列表的示例程序。通过HTTP服务器展示产品信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值