Search code examples
databasenode.jscouchdbcloudant

How can I get and show data from CouchDB Cloudant with pure NodeJS?


I think this is basic question for many beginning developers. I had the same question.

How can I easily send request from PURE NodeJS code and get simple JSON? And how can I get send data to web response?


Solution

  • At first send request to database and show to console:

    https://nodejs.org/api/https.html

    var https = require('https');
    
    var db_options = {
        "auth": "{{name}}:{{pwd}}",
        "host": "{{name}}.cloudant.com",
        "port": "443", // or 80
        "path": "/{{db_name}}/_all_docs"
    }
    
    https.request(db_options, function(response) { // or http
    
        var out = '';
    
        response.on('data', function(data) {
            out += data;
        });
    
        response.on('end', function() {
            console.log(out);
        })
    
    })
    .on('error', function(err) {
        console.log(err);
    })
    .end();
    

    Then simply wrap it to web server according basic example Node.js:

    https://nodejs.org/api/synopsis.html

    var http = require('http');
    
    var server_ipAddr = '127.0.0.1';
    var server_port = 8080;
    
    var server_http = http.createServer(function(req, res) {
    
    ...
    
          response.on('end', function() {
            res.end(out); // <-- add or replace "console.log(out);"
          })
    
    ...
    
    
    }).listen(server_port, server_ipAddr);
    

    You can use these codes separately. Together looks like this:

    var http = require('http');
    
    var server_ipAddr = '127.0.0.1';
    var server_port = 8080;
    
    var server_http = http.createServer(function(req, res) {
    
        var https = require('https');
    
        var db_options = {
            "auth": "{{name}}:{{pwd}}",
            "host": "{{name}}.cloudant.com",
            "port": "443", // or 80
            "path": "/{{db_name}}/_all_docs"
        }
    
        https.request(db_options, function(response) { // or http
    
            var out = '';
    
            response.on('data', function(data) {
                out += data;
            });
    
            response.on('end', function() {
    
                console.log(out);
    
                res.end(out);
    
            })
    
        })
        .on('error', function(err) {
            console.log(err);
        })
        .end();
    
    }).listen(server_port, server_ipAddr);
    

    And if you run it you get something like this:

    $ node cloudant.get.alldoc.js
    {"total_rows":148,"offset":0,"rows":[
    {"id":"0fdda996e7b4f11b8a5ab6c9aa002151","key":"0fdda996e7b4f11b8a5ab6c9aa002151","value":{"rev":"1-6eb8654a7ac5a7cb810e87ef30b2a9d5"}},
    ...
    ]}
    

    I hope this helps someone.