如何使用参数在spawn / exec子进程中运行mongodump命令

时间:2017-05-30 04:24:00

标签: node.js mongodb shell child-process mongodump

我需要使用以下参数运行mongodump命令

    var dbhost = mongoose.connection.host || "127.0.0.1",
                    dbport = mongoose.connection.port,
                    dbname = mongoose.connection.name,
                    dbuser = mongoose.connection.options.user,
                    dbpass = mongoose.connection.options.pass,
                    backupPath = path,
                    date = new Date(),
                    currentDate =  date.toLocaleString(),
                    backupFileName ='DBBACKUP-'+currentDate;

如何将上述变量传递给子进程

我已尝试使用以下代码

var backupDB = spawn('mongodump --host '+dbhost+' --port '+dbport+' --username '+dbuser+' --password '+dbpass+' --db '+dbname+' --archive=backupFileName.gz --gzip');
backupDB.stdout.on('data',function(data){ console.log('stdout: ' + data);

它抛出了这个错误

error: uncaughtException: spawn mongodump --host 127.0.0.1 --port 27017 --username --password --db mydb --archive=backupFileName.gz --gzip ENOENT 

2 个答案:

答案 0 :(得分:1)

根据the fine manualspawn()采用命令的名称,数组参数传递给该命令:

var backupDB = spawn('mongodump', [
  '--host',     dbhost,
  '--port',     dbport,
  '--username', dbuser,
  '--password', dbpass,
  '--db',       dbname,
  '--archive=backupFileName.gz',
  '--gzip'
]);

答案 1 :(得分:0)

我已经尝试过了,但效果很好

var backupDB = exec('mongodump --host='+dbhost+' --port='+dbport+' --username='+dbuser+' --password='+dbpass+' --db='+dbname+' --archive='+backupPathDir+'/'+backupFileName+'.gz  --gzip');
            backupDB.stdout.on('data',function(data){
                console.log('stdout: ' + data);// process output will be displayed here
            });