Use CouchDB with Node.js library

641 Views Asked by At

CouchDB uses javascript to validate, query, do map-reduce and so on. I'd like to know is there any way to use node.js library in these javascript functions? Such as use require('http') or some third party modules installed with npm.

Thanks.

2

There are 2 best solutions below

4
On

No, there isn't a way to use external JavaScript from a Node module inside of CouchDb. You can do some limited sharing: http://wiki.apache.org/couchdb/HTTP_view_API#Sharing_Code_Between_Views

Node is a platform that is exposed to a Javascript language binding, so the "goodness" of Node is in the execution environment.

And while there is a way to write Views using Python, I'm not aware of anything similar for Node.

4
On

You can use Node.js libraries as long as they don't require Node.js-specific libraries like http. For example, async works in CouchDB. Rule of thumb: if it's intended for the server and the client, you should be good.

You can use CommonJS's module.exports and exports[something] patterns to share code between views. Check out the documentation for more details.

For example, consider this view:

{
  _id:"_design/test",
  views: {
    lib: {
      test: "exports.guests = 42;"
    },
    fish_per_person: {
      map: function(doc){
        var guests = require('views/lib/test').guests; // 42
        emit(doc.number_of_fish, doc.number_of_fish / guests);
      }
    }
  }
}

The fish_per_person view requires the value guests exported in lib/test.