您现在的位置:首页 --> JavaScript --> Nodejs和MongoDB初体验
Nodejs和MongoDB初体验
浏览:5508次 出处信息
学习了一下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"); |
建议继续学习:
- 为什么我们要从 NodeJS 迁移到 Ruby on Rails (阅读:5938)
- MongoDB与内存 (阅读:5775)
- JavaScript,只有你想不到 (阅读:5806)
- 使用socket.io和node.js搭建websocket应用 (阅读:4875)
- 我为什么选择MongoDB (阅读:4388)
- 白话MongoDB(一) (阅读:4321)
- nodejs教程:配置nodejs.exe的windows目录结构 (阅读:4240)
- MySQL和MongoDB设计实例对比 (阅读:4226)
- node.js调研与服务性能测试 (阅读:4175)
- 基于express+socket.io的nodejs聊天室 (阅读:4072)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
扫一扫订阅我的微信号:IT技术博客大学习
<< 前一篇:新浪操作textarea的工具函数
后一篇:JavaScript 测试覆盖率检测工具 >>
文章信息
- 作者:小寒 来源: 记事本
- 标签: MongoDB Nodejs
- 发布时间:2011-01-18 22:18:35
建议继续学习
近3天十大热文
-
[882] WordPress插件开发 -- 在插件使用 -
[136] 解决 nginx 反向代理网页首尾出现神秘字 -
[57] 整理了一份招PHP高级工程师的面试题 -
[55] 用 Jquery 模拟 select -
[54] Innodb分表太多或者表分区太多,会导致内 -
[54] 分享一个JQUERY颜色选择插件 -
[54] 如何保证一个程序在单台服务器上只有唯一实例( -
[52] CloudSMS:免费匿名的云短信 -
[52] jQuery性能优化指南 -
[51] 海量小文件存储
