您现在的位置:首页 --> JavaScript --> Nodejs和MongoDB初体验
Nodejs和MongoDB初体验
浏览:5084次 出处信息
学习了一下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 (阅读:5507)
- MongoDB与内存 (阅读:5456)
- JavaScript,只有你想不到 (阅读:5259)
- 使用socket.io和node.js搭建websocket应用 (阅读:4463)
- 我为什么选择MongoDB (阅读:3936)
- MySQL和MongoDB设计实例对比 (阅读:3764)
- nodejs教程:配置nodejs.exe的windows目录结构 (阅读:3742)
- node.js调研与服务性能测试 (阅读:3722)
- 白话MongoDB(一) (阅读:3702)
- 基于express+socket.io的nodejs聊天室 (阅读:3654)
QQ技术交流群:445447336,欢迎加入!
扫一扫订阅我的微信号:IT技术博客大学习
扫一扫订阅我的微信号:IT技术博客大学习
<< 前一篇:新浪操作textarea的工具函数
后一篇:JavaScript 测试覆盖率检测工具 >>
文章信息
- 作者:小寒 来源: 记事本
- 标签: MongoDB Nodejs
- 发布时间:2011-01-18 22:18:35
建议继续学习
近3天十大热文
-
[82] memory prefetch浅析
-
[53] 转载:cassandra读写性能原理分析
-
[51] 深入浅出cassandra 4 数据一致性问
-
[51] 基本排序算法的PHP实现
-
[46] 字符引用和空白字符
-
[42] Inline Form Labels
-
[41] 获取Dom元素的X/Y坐标
-
[41] MySQL半同步存在的问题
-
[40] javascript插入样式
-
[40] JS中如何判断字符串类型的数字