您好,欢迎访问一九零五行业门户网

在Mac OS下使用Node.js的简单教程_node.js

这里有一篇很好的 node.js 介绍文章 great nodejs intro ,它将给你一个非常方便的介绍 node.js 和 couchdb,并给出一个实例实现 rest 的服务用于执行书签的 crud 操作,使用 couchdb 作为数据库。
本文将介绍在 mac os x 下安装并开始使用 node.js ,这个过程大概需要 30 分钟左右的时间,其中我们还将安装 couchdb,并实现基于 couchdb 的 rest api。
本文假设你机器上已经装有git,如果还没有,请参考此文进行安装。
安装 node.js 和 npm
最简单的方法是在 node.js 的官网上通过 the nodejs download section 页面并选择 mac 下的安装程序,它将在你的机器上安装 node.js 和 npm (node package manager). 
 安装成功后你就可以使用 node 和 npm 命令了。
安装 couchdb
因为本文需要使用 couchdb 来存储对象,因此还需要安装 couchdb.
安装 couchdb 稍微麻烦一些,因为我们需要下载源码然后编译i,在此之前需要先安装 homebrew ,请执行以下命令:
git clone https://github.com/mxcl/homebrew.gitcd homebrew/binbrew install autoconf automake libtoolbrew install couchdb
重要的提示:couchdb 之前报出一个问题可能会阻止你安装,要修复这个问题需要手工编辑 ~/couch/homebrew/library/formula/couchdb.rb 文件,编辑内容如下:
复制代码 代码如下:
require 'formula'
class couchdb welcome, enter .help if you're lost.> connecting to 127.0.0.1 on port 8000. http://127.0.0.1:8000/> \jsonhttp://127.0.0.1:8000/>
访问 rest 服务
在 http-console 中,要执行 get 请求只需要输入 get /bookmarks 即可:
http://127.0.0.1:8000/> get /bookmarkshttp/1.1 200 okdate: sun, 01 apr 2012 17:23:27 gmtserver: journey/0.4.0content-type: application/json;charset=utf-8content-length: 16connection: keep-alive { bookmarks: []}
你也可以使用 json 的片段来执行 post 请求:
http://127.0.0.1:8000/> post /bookmarks... { url: http://nodejs.org }http/1.1 200 okdate: thu, 05 apr 2012 11:45:55 gmtserver: journey/0.4.0content-type: application/json;charset=utf-8content-length: 91connection: keep-alive { bookmark: { _id: 'wd-g-1', resource: 'bookmark', url: 'http://nodejs.org' }}
然后再次执行 get 请求,你就可以看到新插入的数据了:
http://127.0.0.1:8000/> get /bookmarkshttp/1.1 200 okdate: sun, 01 apr 2012 17:23:27 gmtserver: journey/0.4.0content-type: application/json;charset=utf-8content-length: 16connection: keep-alive { bookmarks: [ { _rev: '1-cfced13a45a068e95daa04beff562360', _id: 'wd-g-1', resource: 'bookmark', url: 'http://nodejs.org' } ]}
其它类似信息

推荐信息