Skip to content

Instantly share code, notes, and snippets.

@nickpoorman
Created July 9, 2014 21:15
Show Gist options
  • Save nickpoorman/0d6271162956b95adc38 to your computer and use it in GitHub Desktop.
Save nickpoorman/0d6271162956b95adc38 to your computer and use it in GitHub Desktop.
Simple repl for rethinkdb
/**
* simple repl for the database
*/
var r = require('rethinkdb');
var inspect = require('util').inspect;
var connectOpts = {
host: process.HOST || '127.0.0.1',
port: process.PORT || 28015,
};
if (process.DB) connectOpts.db = process.DB;
r.connect(connectOpts, function(err, conn) {
if (err) {
console.log('Error: ', err);
process.exit(1);
}
var readline = require('readline'),
rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('> ');
rl.prompt();
var cmd = '';
rl.on('line', function(line) {
// pause the stream
rl.pause();
line = line.trim();
// check to see if run() is not at the end
if (!(/\.run\(\)$/.test(line))) {
// did not end with run, so append to the cmd
cmd = cmd + line;
rl.setPrompt('>> ');
rl.prompt();
rl.resume();
return;
}
// remove run from the end of line and add it to the command
line = line.replace(/\.run\(\)$/, '');
cmd = cmd + line;
// execute the query, then spit out the result
var re = eval(cmd);
cmd = ''; // reset command
re.run(conn, function(err, cursor) {
if (typeof cursor.toArray === 'function') {
cursor.toArray().then(function(agg) {
console.log(JSON.stringify(agg, null, 2));
// unpause the stream
rl.setPrompt('> ');
rl.prompt();
rl.resume();
}).error(console.log);
} else {
console.log(JSON.stringify(cursor, null, 2));
rl.setPrompt('> ');
rl.prompt();
rl.resume();
}
});
}).on('close', function() {
console.log();
console.log('Closing connection!');
process.exit(0);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment