温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Nodejs结合MongoDB

发布时间:2020-06-10 08:07:19 来源:网络 阅读:568 作者:duoku 栏目: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");

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI