简体   繁体   中英

Node.js run command line (child_process?)

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

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

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

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.

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

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

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

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

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 .

The shell is incorrect here:

{ shell: '/bin/bash' }

It should be:

{ shell: 'CMD.EXE' }

Because in the beginning of your post, you tell that you run 2 commands in the Windows command line , which indicates you are not using Bash, which is (usually) not installed on Windows.

(I know my answer comes almost two years later than the question, but I wrote it in case anyone still reads this.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM