由nodejs传入shell的尴尬字符串

时间:2017-04-18 10:19:19

标签: node.js regex shell whitespace

我一直在使用millermedeiros编写的脚本库(感谢他)在nodejs中同步执行多个shell命令。

但有趣的是,无论我尝试过什么,我都无法传递包含空格的字符串。

所以,这是lib代码(./shellHelper.js):

exports.series = function(cmds, cb){
var execNext = function(){
    exports.exec(cmds.shift(), function(err){
        if (err) {
            cb(err);
        } else {
            if (cmds.length) execNext();
            else cb(null);
        }
    });
};
execNext();
};

这是我的代码(./gitcommit.js):

var shell = require('./shellHelper');
...
var regex = '/\s([A-Z0-9])\w+/g';
var message = input.replace(regex); //input string is coming from prompt module
...
var command1 = 'git add .';
var command2 = 'git commit -m \"' + message + '\"';
var command3 = 'git push origin master';
...
shell.series([ command1, command2, command3], function(err){
   console.log('executed many commands in a row');
   console.log(command2);
  });
});

它确实有效,除非我输入带空格的消息。控制台标准输出是:

$ ..\nodejs (master)
$ node gitcommit.js
Enter commit message :
prompt: name:  something contains white spaces
error: pathspec 'contains' did not match any file(s) known to git.
error: pathspec 'white' did not match any file(s) known to git.
error: pathspec 'spaces"' did not match any file(s) known to git.
executed many commands in a row
git commit -m "something contains white spaces"

0 个答案:

没有答案