• Stars
    star
    364
  • Rank 117,101 (Top 3 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 15 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A new CouchDB module following node.js idioms

Now maintained and active!!!

I'd like to thank Felix for creating this and hope you find it useful when working with node and couchDB.

Node.js CouchDB module

A thin node.js idiom based module for CouchDB's REST API that tries to stay close to the metal.

Tutorial

Installation is simple from NPM:

$ npm install felix-couchdb

To use the library, create a new file called my-couch-adventure.js:

var
  util = require('util'),
  couchdb = require('felix-couchdb'),
  client = couchdb.createClient(5984, 'localhost'),
  db = client.db('my-db');

db
  .create(function(er){
    if (er) throw new Error(JSON.stringify(er));
    util.puts('Created new db.');
  });

db
  .saveDoc('my-doc', {awesome: 'couch fun'}, function(er, ok) {
    if (er) throw new Error(JSON.stringify(er));
    util.puts('Saved my first doc to the couch!');
  });

db
  .getDoc('my-doc', function(er, doc) {
    if (er) throw new Error(JSON.stringify(er));
    util.puts('Fetched my new doc from couch:');
    util.p(doc);
  });

If you are wondering if there is a race-condition in the above example, the answer is no. Each couchdb.Client uses an internal queue for its requests, just like http.Client. This guarantees ordering. If you want to perform multiple requests at once, use multiple couchdb.Client instances.

API Documentation

Callbacks

All asynchronous functions are performed with callbacks. Callback functions are always the last argument, and always receive one or two arguments. The first argument is an error object or null if no error occurs. The second is the data returned by the function in question, if appropriate.

The callback argument is optional. If not supplied, then errors and return values will be silently ignored.

For example:

client.request('/_uuids', {count: 2}, function (er, data) {
  if (er) {
    // an error occurred.  Attempt to handle it or rethrow, or whatever.
  } else {
    // data is the result of the request.
  }
})

couchdb.toJSON(data)

Identical to JSON.stringify(), except that function values will be converted to strings like this:

couchdb.toJSON({
  foo: 'bar',
  fn: function(a, b) {
    p(a, b);
  }
})
// => {"foo":"bar","fn":"function (a, b) {\n    p(a, b);\n  }"}

node-couchdb uses this function everywhere for JSON serialization, this makes it convenient to embed functions.

couchdb.toQuery(query)

Identical to querystring.stringify(), except that boolean values will be converted to "true" / "false" strings like this:

couchdb.toQuery({
  include_docs: true
})
// => include_docs=true

node-couchdb uses this function everywhere for query serialization, this helps since couchdb expects boolean values in this format.

couchdb.toAttachment(file, cb)

Takes the path of a file and callback receives a JS object suitable for inline document attachment:

couchdb
  .toAttachment(__filename, function(er, r) {
    if (er) throw new Error(JSON.stringify(er));
    // r => {"content_type":"text/javascript","data":"dmFyCiAgs...="}
  });

Check lib/dep/mime.js for a list of recognized file types.

couchdb.createClient([port, host, user, pass, maxListeners, secure])

Creates a new couchdb.Client for a given port (default: 5984) and host (default: 'localhost'). This client will queue all requests that are send through it, so ordering of requests is always guaranteed. Use multiple clients for parallel operations.

If the optional user and pass arguments are supplied, all requests will be made with HTTP Basic Authorization

If the optional maxListeners is supplied - module uses emitter.setMaxListeners method. It may be useful if you use many couchdb requests and don't want to see warnings. Default Node.js value for this == 11 listeners; if maxListeners == 0 then warnings are off.

If the optional secure is supplied as true, then the https transport is used. Note that https is usually serviced on port 443. This is useful when using cloud-based CouchDB services such as Cloudant where their API is hosted on a https platform e.g.

  client = couchdb.createClient(443, 'username.cloudant.com','username','password',0,true),

client.host

The host this client is connecting to. READ-ONLY property

client.port

The port this client is connecting to. READ-ONLY property

client.request(path, [query], cb)

Sends a GET request with a given path and query. Callback receives a result object. Example:

client.request('/_uuids', {count: 2})

client.request(method, [path, query])

Sends a request with a given method, path and query. Callback receives a result object. Example:

client.request('get', '/_uuids', {count: 2})

client.request(options, cb)

Sends a request using the given options and callback receives a result object. Available options are:

  • method: The HTTP method (default: 'GET')
  • path: The request path (default: '/')
  • headers: Additional http headers to send (default: {})
  • data: A JS object or string to send as the request body (default: '')
  • query: The query options to use (default: {}).
  • requestEncoding: The encoding to use for sending the request (default: 'utf8')
  • responseEncoding: The encoding to use for sending the request. If set to 'binary', the response is emitted as a string instead of an object and the full option is ignored. (default: 'utf8')
  • full: By default the callback receives the parsed JSON as a JS object. If full is set to true, a {headers: ..., json: ...} object is yielded instead. (default: false)

Example:

client.request({
  path: '/_uuids',
  query: {count: 5},
  full: true
}, callback);

client.allDbs()

Wrapper for GET /_all_dbs.

client.config()

Wrapper for GET /_config.

client.uuids([count])

Wrapper for GET /_uuids. count is the number of uuid's you would like CouchDB to generate for you.

client.replicate(source, target, [options])

Wrapper for POST /_replicate. source and target are references to the databases you want to synchronize, options can include additional keys such as {create_target:true}.

client.stats([group, key])

Wrapper for GET /_stats. group and key can be used to limit the stats to fetch.

client.activeTasks()

Wrapper for GET /_active_tasks.

client.db(name)

Creates a new couchdb.Db instance for a database with the given name.

db.name

The name of the db this instance is tied to. READ-ONLY property

db.client

A reference to the couchdb.Client this instance is tied to. READ-ONLY property

db.request(options)

Same as client.request, but the path option gets automatically prefixed by '/db-name'.

db.exists(cb)

Callback called with a boolean indicating whether this db exists or not.

db.info(cb)

Wrapper for GET /db-name.

db.create(cb)

Wrapper for PUT /db-name.

db.remove()

Wrapper for DELETE /db-name.

db.getDoc(id, [rev], [attachments])

Wrapper for GET /db-name/doc-id[?rev=][&attachments=]. Fetches a document with a given id and optional rev and/or attachments from the database.

db.saveDoc(id, doc)

Wrapper for PUT /db-name/doc-id. Saves a json doc with a given id.

db.saveDoc(doc)

Same as the above, but the id can either a property of doc, or omitted to let CouchDB generate a uuid for this new document.

db.removeDoc(id, rev)

Deletes document id with rev from the db.

db.copyDoc(srcId, destId, [destRev])

Copies document srcId to destId. If destId already exists, you need to supply destRev to overwrite it.

db.bulkDocs(data)

Wrapper for POST /db-name/_bulk_docs.

db.saveDesign(design, doc)

A convenience wrapper for saveDoc() that prefixes the document id with '_design/'+design. Useful for storing views like this:

db
  .saveDesign('my-design', {
    views: {
      "my-view": {
        map: function() {
          emit(null, null)
        }
      }
    }
  })

db.saveAttachment(file, docId, options)

Attaches a file to a given docId. Available options:

  • name: The name of the attachment. (default: path.basename(file))
  • contentType: The content type to associate with this attachment (default: see lib/dep/mime.js)
  • rev: If the docId already exists, you have to supply its current revision.

db.removeAttachment(docId, attachmentId, docRev)

Delete attachment attachmentId from doc docId with docRev.

db.getAttachment(docId, attachmentId, cb)

Loads the attachment attachmentId from docId. The callback receivesthe binary content of the attachment. There is no streaming, don't use this with large files.

db.allDocs(query)

Wrapper for GET /db-name/_all_docs. query allows to specify options for this view.

db.allDocsBySeq(query)

Wrapper for GET /db-name/_all_docs_by_seq.

Replaced by GET /db-name/_changes as of CouchDB 0.11. Consider using db.changes or db.changesStream.

db.compact([design])

Wrapper for POST /db-name/_compact/design-name. design provides the name of the design to invoke compact for, otherwise the whole db is used.

db.tempView(data, query)

Wrapper for POST /db-name/_temp_view.

db.viewCleanup(data, query)

Wrapper for POST /db-name/_view_cleanup.

db.view(design, view, [query], [cb])

Wrapper for GET /db-name/_design/design-name/_view/view-name. Fetches all documents for the given design and view with the specified query options.

db.list(design, list, view, [query], [cb])

Wrapper for GET /db-name/_design/design-name/_list/list-name/view-name. Fetches all documents for the given design and view with the specified query options.

db.changes([query])

Wrapper for GET /db-name/_changes. This can be used for long-polling or one-time retrieval from the changes feed. If you want to get a continuous stream of changes, use the db.changesStream() function instead.

db.changesStream([query])

Returns an events.EventEmitter stream that emits the following events:

  • data(change): Emitted for each change line in the stream. The change parameter holds the change object.
  • heartbeat: Emitted for each heartbeat send by CouchDB, no need to check this for most stuff.
  • end(hadError): Emitted if the stream ends. This should not happen unless you manually invoke stream.close().

See the CouchDB docs for available query parameters.

Important: This function uses its own http client for making requests, so unlike all other functions it does not go through the internal request queue.

Todo

  • http status, message and parsed body for errors
  • db.saveAttachment(file, docId, options) take file descriptor
  • Implement Authentication

Limitations

  • Streaming attachments is not supported at this point (patches welcome)
  • Etags are only available via client.request({full: true})

More Repositories

1

node-style-guide

A guide for styling your node.js / JavaScript code. Fork & adjust to your taste.
JavaScript
4,950
star
2

fgprof

๐Ÿš€ fgprof is a sampling Go profiler that allows you to analyze On-CPU as well as Off-CPU (e.g. I/O) time together.
Go
2,469
star
3

node-ar-drone

A node.js client for controlling Parrot AR Drone 2.0 quad-copters.
JavaScript
1,755
star
4

node-dateformat

A node.js package for Steven Levithan's excellent dateFormat() function.
JavaScript
1,297
star
5

node-memory-leak-tutorial

A tutorial for debugging memory leaks in node
JavaScript
909
star
6

httpsnoop

Package httpsnoop provides an easy way to capture http related metrics (i.e. response time, bytes written, and http status code) from your application's http.Handlers.
Go
891
star
7

fgtrace

fgtrace is an experimental profiler/tracer that is capturing wallclock timelines for each goroutine. It's very similar to the Chrome profiler.
Go
878
star
8

faster-than-c

Talk outline: Faster than C? Parsing binary data in JavaScript.
JavaScript
836
star
9

node-dirty

A tiny & fast key value store with append-only disk log. Ideal for apps with < 1 million records.
JavaScript
625
star
10

node-stack-trace

Get v8 stack traces as an array of CallSite objects.
JavaScript
449
star
11

nodeguide.com

My unofficial and opinionated guide to node.js.
CSS
371
star
12

sqlbench

sqlbench measures and compares the execution time of one or more SQL queries.
Go
361
star
13

node-sandboxed-module

A sandboxed node.js module loader that lets you inject dependencies into your modules.
JavaScript
344
star
14

node-require-all

An easy way to require all files within a directory.
JavaScript
300
star
15

tcpkeepalive

Go package tcpkeepalive implements additional TCP keepalive control beyond what is currently offered by the net pkg.
Go
238
star
16

node-paperboy

A node.js module for delivering static files.
JavaScript
234
star
17

godrone

GoDrone is a free software alternative firmware for the Parrot AR Drone 2.0.
Go
204
star
18

node-romulus

Building static empires with node.js.
JavaScript
157
star
19

node-gently

A node.js module that helps with stubbing and behavior verification.
JavaScript
142
star
20

node-combined-stream

A stream that emits multiple other streams one after another.
JavaScript
142
star
21

cakephp-authsome

Auth for people who hate the Auth component
PHP
123
star
22

pprofutils

Go
122
star
23

node-growing-file

A readable file stream for files that are growing.
JavaScript
106
star
24

node-graphite

A node.js client for graphite.
JavaScript
105
star
25

node-cross-compiler

Simplified cross compiling for node.js using vagrant.
Shell
105
star
26

pidctrl

A PID controller implementation in Golang.
Go
96
star
27

node-m3u

A node.js module for creating m3u / m3u8 files.
JavaScript
89
star
28

debuggable-scraps

MIT licensed code without warranty ; )
PHP
79
star
29

traceutils

Code for decoding and encoding runtime/trace files as well as useful functionality implemented on top.
Go
62
star
30

node-delayed-stream

Buffers events from a stream until you are ready to handle them.
JavaScript
56
star
31

go-redis

A redis implementation written in Go.
Go
53
star
32

nodelog

A node.js irc bot that logs a channel
JavaScript
49
star
33

flame-explain

A PostgreSQL EXPLAIN ANALYZE visualizer with advanced quirk correction algorithms.
TypeScript
46
star
34

node-stream-cache

A simple way to cache and replay readable streams.
JavaScript
45
star
35

node-utest

The minimal unit testing library.
JavaScript
42
star
36

go-cpu-utilization

Go
39
star
37

go-xxd

The history of this repo demonstrates how to take a slow xxd implementation in Go, and make it faster than the native version on OSX/Linux.
Go
38
star
38

vim-nodejs-errorformat

Vim Script
36
star
39

tweets

C
35
star
40

go-ardrone

Parrot AR Drone 2.0 drivers and protocols written in Go.
Go
33
star
41

dotfiles

My setup. Pick what you like.
Lua
31
star
42

node-buffy

A module to read / write binary data and streams.
JavaScript
31
star
43

node-urun

The minimal test runner.
JavaScript
31
star
44

node-multipart-parser

A fast and streaming multipart parser.
JavaScript
30
star
45

node-require-like

Generates require functions that act as if they were operating in a given path.
JavaScript
29
star
46

benchmore

Go
28
star
47

node-nix

Node.js bindings for non-portable *nix functions
JavaScript
28
star
48

node-fake

Test one thing at a time, fake the rest.
JavaScript
28
star
49

node-bash

Utilities for using bash from node.js.
JavaScript
25
star
50

gounwind

Experimental go stack unwinding using frame pointers.
Go
25
star
51

node-microtest

Unit testing done right.
JavaScript
23
star
52

pgmigrate

pgmigrate implements a minimalistic migration library for postgres.
Go
22
star
53

node-comment

Proof of concept - Long polling message queue with CouchDB for persistence.
JavaScript
21
star
54

node-ugly

A hack so unbelievably ugly, yet so hard to resist
JavaScript
20
star
55

advent-2021

Advent of Go Profiling 2021.
Go
19
star
56

open-source-contribution-guide

A guide for anybody interested in contribution to my open source projects.
18
star
57

go-patch-overlay

WIP
Go
17
star
58

node-channel

A general purpose comet server written in node.js
JavaScript
16
star
59

node-active-x-obfuscator

A module to (safely) obfuscate all occurrences of the string 'ActiveX' inside any JavaScript code.
JavaScript
16
star
60

gotraceanalyzer

Command gotraceanalyzer turns golang tracebacks into useful summaries.
Go
14
star
61

go-observability-bench

Measure the overheads of various observability tools, especially profilers.
Jupyter Notebook
14
star
62

rebel-resize

Dynamic image resizing server written during my web rebels 2012 live coding.
JavaScript
13
star
63

node-fast-or-slow

Are your tests fast or slow? A pragmatic testing framework.
JavaScript
13
star
64

cl

Quickly clone git repositories into a nested folders like GOPATH.
Go
13
star
65

node-lazy-socket

A stateless socket that always lets you write().
JavaScript
13
star
66

raleigh-workshop-08

Code repository for the Raleigh, NC CakePHP workshop
PHP
12
star
67

node-deferred

Dojo deferreds as a nodejs module - Work in Progress
JavaScript
12
star
68

node-oop

Simple & light-weight oop.
JavaScript
11
star
69

node-win-iap

Verifies windows store receipts.
JavaScript
10
star
70

goardronefirmware

Open source firmware for the Parrot AR Drone 2.0 written in Go.
Go
10
star
71

node-far

https://github.com/felixge/node-far
JavaScript
10
star
72

node-convert-example

Node.js image resizing demo. One version with and one version without in-memory caching.
10
star
73

couchdb-benchmarks

some benchmark scripts for testing CouchDB performance
PHP
10
star
74

node-socketio-benchmark

A WebSocket / LongPolling simulation to estimate users / core
JavaScript
9
star
75

gpac

Mirror of https://gpac.svn.sourceforge.net/svnroot/gpac/trunk/gpac + my patches
C
9
star
76

node-passthrough-stream

An example of a passthrough stream for node.js
JavaScript
9
star
77

node-http-recorder

A little tool to record and replay http requests.
JavaScript
9
star
78

node-cluster-isolatable

Isolate workers so they only handle one request at a time. Useful for file uploads.
JavaScript
8
star
79

nodecopter-ssh-tunnel

Bash scripts for controlling an AR Drone over the internet via ssh tunneling.
Shell
8
star
80

makefs

WIP - come back later.
Go
8
star
81

node-unicode-sanitize

JavaScript
8
star
82

felixge.de

My site and blog.
HTML
7
star
83

dump

A code dump of things not worth putting into their own repo.
Go
7
star
84

ooti

A kickass test suite for node.js
JavaScript
6
star
85

go-cgo-finalizer

Demonstrates using runtime.SetFinalizer to free cgo memory allocations.
Go
6
star
86

focus-app

Helps you focus by hiding all your windows except the ones you are currently working in.
Objective-C
6
star
87

gopg

Go
5
star
88

isalphanumeric

A small arm64 SIMD adventure for gophers.
Go
5
star
89

dd-trace-go-demo

A simple application to show how to use dd-trace-go's tracer and profiler.
Go
5
star
90

profiler-simulator

Go
5
star
91

talks

Source and slides for my presentations.
PLpgSQL
5
star
92

node-redis-pool

A simple node.js redis pool.
JavaScript
5
star
93

countermap

Go
5
star
94

pprof-breakdown

Go
5
star
95

proftest

proftest is a C application for testing the quality of different operating system APIs for profiling.
C
5
star
96

s3.sh

Bash functions for Amazon S3. (Not complete, just scratching my itch)
Shell
5
star
97

can

Nothing to see here yet.
Go
4
star
98

js-robocom

A robocom inspired programming game for JavaScript
JavaScript
4
star
99

log

nothing to see here yet
Go
4
star
100

dd-prof-upload

Go
4
star