【问题标题】:Allowing for user-provided executive string with child_process.spawn()使用 child_process.spawn() 允许用户提供的执行字符串
【发布时间】:2016-10-08 05:55:28
【问题描述】:

使用 node.js child_process#spawn,它可能看起来像这样:

const child = cp.spawn('npm', ['install','-D','suman'], {});

或者像这样:

const child = cp.spawn('foo', ['bar','baz'], {});

我的 lib 的用户将提供一个命令字符串,类似于 NPM 脚本。

一个 NPM 脚本在 package.json 中可能看起来像这样

scripts : {
  'test': 'npm test'
}

在我的库中,用户可能会提供任何东西,例如:

'watchProcess': {
  'a' :{
     script: 'foo bar baz',
     include: [],
     exclude: []
   },
 'b' :{
     script: 'node rolo cholo',
     include: [],
     exclude: []
   },

 'c' :{
     script: 'java biz bang',
     include: [],
     exclude: []
   }

}

我需要做任何特别的事情来解析watchProcess.a.script/watchProcess.b.script/watchProcess.c.script 字符串吗? 或者我只是通过空格分割来标记它,然后放入 child_process.spawn?

【问题讨论】:

    标签: node.js child-process


    【解决方案1】:

    您可以在关键脚本中获取您的字符串并将它们标记化(如您所说),您无能为力!

    也许您想从字符串中挑选出某些字符,但大多数时候不需要。

    【讨论】:

      【解决方案2】:

      是的,鉴于我对此的简短测试,似乎只需要以下内容:

      const cp = require('child_process');
      
      const execString = 'npm install --save suman';
      
      const execStringArray = String(execString).split(/\s+/);  <<< key part
      const executable = execStringArray.shift();
      
      const child = cp.spawn(executable, execStringArray, {});
      

      最终以纯文本形式显示:

      const child = cp.spawn('npm', ['install','--save-dev','suman'], {});
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-28
        • 2021-01-11
        • 1970-01-01
        • 1970-01-01
        • 2011-12-14
        • 2021-05-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多