james_womack
james_womack

Reputation: 10306

Starting couchdb from node.js via exec or spawn

I'm attempting to start couchdb from node.js if it hasn't already been started. Code like the following works for basic commands like pwd but not for couchdb:

var sys = require('util')
var exec = require('child_process').exec;
var child;

// executes `pwd`
child = exec("pwd", function (error, stdout, stderr) {
  sys.print('stdout: ' + stdout);
  sys.print('stderr: ' + stderr);
  if (error !== null) {
    console.log('exec error: ' + error);
  }
});

I've tried using 'couchdb' & '/usr/local/bin/couchdb' as arguments to exec.

Upvotes: 2

Views: 510

Answers (1)

james_womack
james_womack

Reputation: 10306

I have a working example now using CoffeeScript:

childproc = require "child_process"    
couchdb = childproc.spawn "couchdb"
couchdb.stdout.setEncoding "utf8"
buffer = ""

couchdb.stdout.on "data", (data) ->
  lines = (buffer + data).split(/\r?\n/)
  buffer = lines.pop()
  lines.forEach (line, index) ->
    console.log line

couchdb.stdout.on "end", ->
  if buffer.length > 0
      console.log buffer
      buffer = ""
    console.log 'process ended'

See my gist for a fuller example in CS, Iced CS & JS

EDIT Here is the ouput in Javascript:

var buffer, childproc, couchdb;

childproc = require("child_process");

couchdb = childproc.spawn("couchdb");

couchdb.stdout.setEncoding("utf8");

buffer = "";

couchdb.stdout.on("data", function(data) {
  var lines;
  lines = (buffer + data).split(/\r?\n/);
  buffer = lines.pop();
  return lines.forEach(function(line, index) {
    return console.log(line);
  });
});

couchdb.stdout.on("end", function() {
  if (buffer.length > 0) {
    console.log(buffer);
    buffer = "";
  }
return console.log('process ended');
});

Upvotes: 2

Related Questions