Node.js运行命令行(child_process?) [英] Node.js run command line (child_process?)

查看:83
本文介绍了Node.js运行命令行(child_process?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Node.js程序,我需要在其中单击按钮,在Windows命令行中运行2个命令.例如,通过单击cmd并输入以下命令,我尝试通过单击按钮自动执行的过程可以手动完成:

I have a Node.js program where I need to, on a button click, run 2 commands in the Windows command line. For example, the process I'm trying to automate by the button click would be doable manually by going to cmd and entering the following commands:

pushd \\myserver.com\folder1\folder2         //Connect to remote server folder structure
mkdir NewFolder                              //Create new folder in the remote folder

我发现很多资源都指向我应该使用"child_process",但是在涉及到shell脚本方面我绝对是迷路的,并且很难弄清楚如何做到这一点.这是我到目前为止的代码:

I've found many resources pointing that I should use 'child_process', but I'm absolutely lost when it comes to shell scripting and am having a really hard time figuring out how to do this. Here's the code I have so far:

var cp = require('child_process');
cp.exec('pushd \\\\myserver.com\\folder1\\folder2\\', { shell: '/bin/bash' }, function(err, stdout, stderr){
    if(err){
        console.log(err);        
    }
});

但是上面的代码仅返回此错误(奇怪地从给定目录中删除了\):

But this above code just returns this error (which oddly removes the '\'s from the given dir):

{ Error: Command failed: pushd \\myserver.com\folder1\folder2\
/bin/bash: line 1: pushd: \myserver.comfolder1folder2: No such file or directory
    at ChildProcess.exithandler (child_process.js:281:12)

  killed: false,
  code: 1,
  signal: null,
  cmd: 'pushd \\\\myserver.com\\folder1\\folder2\\' }
/bin/bash: line 1: pushd: \myserver.comfolder1folder2: No such file or directory

我在这里真的迷路了,不胜感激.您必须使用child_process的任何替代方法也会很有帮助.谢谢!

I'm really lost here and would appreciate any help. Any alternative you have to child_process may also be very helpful. Thank you!

推荐答案

通常,用于字符串的所有转义序列都对单个反斜杠使用'\\'.可以理解,您在这里使用它作为Windows的目录路径.

Usually all the escape sequences used for string uses '\\' for a single backslash. It is understandable you used it here for the directory path for windows.

特别是在JS中,'\\'并非完全像这样

In JS particularly '\\' doesn't exactly work like that

'abc\
def' == 'abcdef' // true

'\a' == 'a' // true

当'\'后面没有特殊含义的字符时,它将被视为LineContinuation.

When a '\' is not followed by a character with any special meaning, it is considered to be a LineContinuation instead.

从错误输出中可以看到,使用'\\\\ myserver.com'被视为'\ myserver.com'.普通的解决方法是将'\\\\'用作单个'\'或将'/'用作路径分隔,我不太确定shell是否会执行它.这是其中一个博客详细解释的内容链接.

As you can see from your error output using '\\\\myserver.com' considered '\myserver.com'. Plain workaround is to use '\\\\' for single '\' or use '/' for path separation which I'm not pretty sure if shell will execute it. This is one of the blogs explains about it in details Link.

这篇关于Node.js运行命令行(child_process?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆