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

荒凉一梦 提交于 2019-12-10 23:59:38

问题


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.


回答1:


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

    //,,,,,,,,,,,,,,,,
}());


来源:https://stackoverflow.com/questions/18090792/shell-command-to-child-process-spawncommand-args-options-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!