Node.JS——服务器端的js语言
shiny 写于 2011-04-19 09:06:33. 后端那些事
index.js
JavaScript代码- var express = require('express');
- var app = express.createServer();
- var db = require('./tea/db');
- db.open({dbName:'comments'});
- app.get('/',function(req,res){
- db.findOne('comments',{},function(records){
- res.send(records);
- });
- });
- app.listen(8001);
/tea/index.js
JavaScript代码
- var tea = exports;
- tea.hello = function(){
- console.log('hello world');
- }
/tea/db.js
JavaScript代码
- var mongo = require('mongodb');
- var tea = tea || {};
- tea.db = exports;
- tea.db.server = '127.0.0.1';
- tea.db.port = 27017;
- tea.db.db = null;
- tea.db.dbName = '';
- tea.db.collection = '';
- tea.db.open = function(mongoInfo,callback){
- this.dbName = mongoInfo.dbName;
- if(!this.db) this.db = new mongo.Db(mongoInfo.dbName, new mongo.Server('127.0.0.1', 27017, {}), {});
- this.db.open(function(err,db){
- this.db = db;
- if(callback) callback(db);
- });
- return this;
- };
- tea.db.find = function(collection,query,callback,isFindOne){
- this.db.collection(collection, function(err, collection) {
- var func = isFindOne ? 'findOne' : 'find';
- collection[func](query,function(err,cursor){
- if(!isFindOne) {
- cursor.toArray(function(err,items){
- if(callback) callback(items);
- });
- }else{
- if(callback) callback(cursor);
- }
- });
- });
- }
- tea.db.findOne = function(collection,query,callback){
- this.find(collection,query,callback,1);
- }
- tea.db.close = function(){
- if(tea.db.db) tea.db.db.close();
- }
- tea.db.hello = function(){
- console.log('Hello World');
- }

本文采用Creative Commons协议,复制本文需遵守三点:1、保留署名(链接);2、非商业性使用;3、再次创作的作品必须以相同的许可协议发布。