Search code examples
node.jsmongodbshellchild-processmongodump

How to run mongodump command in spawn/exec child process with arguments


I need to run mongodump command with below arguments

    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;

how to pass above variables to child process

I've tried with below code

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);

it throwed this error

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

Solution

  • According to the fine manual, spawn() takes the name of a command, and an array of arguments to pass to that command:

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