Search code examples
javascriptnode.jsrsyncspawn

shell command to child_process.spawn(command, [args], [options]) node.js


Basically, I just want to run rsync command on node app.

The raw rsync code is the below:

rsync -r -t -p -o -g -v --progress --delete -l -H /Users/ken/Library/Application Support/Sublime Text 3/Packages /Users/ken/Google Drive/__config-GD/ST3

Firstly, I tried

child_process.exec(command, [options], callback)

but, since the rsync output is long, the buffer exceeded.

So, I tried

child_process.spawn(command, [args], [options])

instead, and stream.pipe out.

var spawn = require('child_process')
        .spawn;
var ps = spawn(command1, args1)
        .stdout
        .pipe(process.stdout);

Although this works as expected, it is way too hard to split every original rsync command to the spawn format. (I copied and paste the command from gRsync tool)

Is there smart way to do this?

Thanks.


Solution

  • Ok, here is the hack;

    Escape white space of the MacDirectory in the terminal shell and javascript/node is very tricky, so I placed _@_ instead of \('\'+whiteSpace).

    (function()
    {
        'use strict';
        //,,,,,,,,,,,,,,
    
        var parseShCmd = function(cmd)
        {
            var cmdA = cmd.split(/ /);
            console.log(cmdA);
            var cmd1 = cmdA[0];
            var args1 = [];
            cmdA.map(function(s, i)
            {
                if (i === 0)
                {
                    console.log('-------------------'); //do nothing
                }
                else
                {
                    args1[i - 1] = cmdA[i].replace(/_@_/g, ' ');
                }
            });
            return [cmd1, args1];
        };
    
        var shCmd = 'rsync' +
            ' -r -t -p -o -g -v --progress --delete -l -H ' +
            '/Users/ken/Library/Application_@_Support/Sublime_@_Text_@_3/Packages ' +
            '/Users/ken/Google_@_Drive/__config-GD/ST3';
        //var shCmd = 'ls -la';
        var cmd1 = parseShCmd(shCmd);
        console.log(cmd1[0]);
        console.log(cmd1[1]);
        console.log('==================');
        var spawn = require('child_process')
            .spawn;
        var ps = spawn(cmd1[0], cmd1[1])
            .stdout
            .pipe(process.stdout);
    
        //,,,,,,,,,,,,,,,,
    }());