如何从node.js以编程方式执行mongodump命令? [英] How do I execute the mongodump command programmatically from node.js?

查看:100
本文介绍了如何从node.js以编程方式执行mongodump命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从node.js以编程方式执行mongodb admin/console命令的最佳方法是什么?具体来说,我想在执行一系列插入操作后使用mongodump导出mongodb集合.像这样:

What is the best way to execute mongodb admin/console commands programmatically from node.js? Specifically, I would like to export a mongodb collection using mongodump after performing a series of inserts. Something like this:

// requires and initializing stuff left out for brevity
db.open(function(err, db) {
    if(!err) {
        db.collection('test', function(err, collection) {
            var docs = [{'hello':'doc1'}, {'hello':'doc2'}, {'hello':'doc3'}];

            collection.insert(docs, {safe:true}, function(err, result) {

                // Execute mongodump in this callback???

            });
        });
    }
});

推荐答案

尝试使用 child_process.spawn(command, args) :

var spawn = require('child_process').spawn;

// ...
  collection.insert(docs, {safe:true}, function(err, result) {
    var args = ['--db', 'mydb', '--collection', 'test']
      , mongodump = spawn('/usr/local/bin/mongodump', args);
    mongodump.stdout.on('data', function (data) {
      console.log('stdout: ' + data);
    });
    mongodump.stderr.on('data', function (data) {
      console.log('stderr: ' + data);
    });
    mongodump.on('exit', function (code) {
      console.log('mongodump exited with code ' + code);
    });
  });
// ...

这篇关于如何从node.js以编程方式执行mongodump命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆