Node.JS: Using spawn to import a database


Example 1: background process:

File api.js

'use strict'
 
const fs = require('fs')
 
module.exports = (req, res) => {
  if (!req.params.action) {
    res.end('');return;
  }
   
  switch(req.params.action){
    case 'import':
         
        var u = req.query.u;
        var p = req.query.p;
        var db = req.query.db;
        var file = req.query.file;
        
        console.log(u,p,db,file)
        
        const { spawn } = require('child_process');
         
        const iinn = fs.openSync(file, 'r+');
        
        const subprocess = spawn('/usr/bin/mysql', [
            '-u' + u,
            '-p' + p,
            db
        ], {
          detached: true,
          stdio: [ iinn ]
        });
        
        subprocess.unref(); 
        res.end()   
    break
  }
}

Example link: http://tutorialspots.com/api/import?u=admin_tutorialspots&p=tutorialspots&db=admin_tutorialspots&file=/root/tutorialspots.sql

Example 2: event when import done

File api.js:

'use strict'
 
const fs = require('fs')
 
module.exports = (req, res) => {
  if (!req.params.action) {
    res.end('');return;
  }
   
  switch(req.params.action){
    case 'importdone':
         
        var u = req.query.u;
        var p = req.query.p;
        var db = req.query.db;
        var file = req.query.file;
        
        console.log(u,p,db,file)
        
        const { spawn } = require('child_process');
         
        const iinn = fs.openSync(file, 'r+');
        
        const subprocess = spawn('/usr/bin/mysql', [
            '-u' + u,
            '-p' + p,
            db
        ], {           
          stdio: [ iinn ]
        });
         
        subprocess.on('close', (code) => {
          console.log(`child process close all stdio with code ${code}`);
          res.end()   
        });
        
    break
  }
}

Example link: http://tutorialspots.com/api/importdone?u=admin_tutorialspots&p=tutorialspots&db=admin_tutorialspots&file=/root/tutorialspots.sql

Leave a Reply