سؤال

I'm currently using nodejs with the child_process module. We're experimenting some weird comportements of batch.

Basically, we just want to copy a file using xcopy command.

For instance, we do:

xcopy "C:/my/path/myfile.test" "C:/my/path/mynewfile.test*" => Does not work. Windows needs backslash
xcopy "C:\my\path\myfile.test" "C:/my/path/mynewfile.test*" => Does not work. We need to escape backslash
xcopy "C:\\my\\path\\myfile.test" "C:/my/path/mynewfile.test*" => Works...

So I have some issues.

  • Why does the source parameter of xcopy need backslash while the destination parameter works with slash?

  • I'm using the spawn function of the child process module. It seems this does not escape anything. I tried to look though the code of nodejs but well... that's not easy! Does the spawn function escape the command?

  • If we do need to escape the command ourselves, then we also want to execute our commands on UNIX. So I presume the escaping method is not the same. And I would not prefer to make a

      if(window)
         escapeshellargWindow(arg)
      else if(unix)
         escapeshellargLinux(arg)
    

Has anyone else got these kind of issues?

هل كانت مفيدة؟

المحلول

Not familiar with Windows, but my guess would be that forward slashes in the first argument might be parsed as being options to the xcopy command. Any following arguments won't be handled as such, and will therefore work.

As for escaping, the issue isn't so much spawn, but more the general way of escaping in literal Javascript strings, using \. So if you use this:

spawn('xcopy', [ 'C:\my\path\myfile.test', ... ])

then this is what spawn will receive (as arguments):

{ '0': 'xcopy', '1': [ 'C:mypathmyfile.test' ] }

And similarly:

> console.log( 'C:\my\path\myfile.test' )
C:mypathmyfile.test

So if you want to add a backslash to a JS string, you need to escape it:

> console.log( 'C:\\my\\path\\myfile.test' )
C:\my\path\myfile.test

But this is only necessary for literal strings in your code (hardcoded in your JS). For strings that are either calculated or passed in some form (like from the command line in process.argv), additional escaping isn't necessary.

Since spawn is agnostic as to what you pass to it, it won't do any escaping itself.

نصائح أخرى

I have found that using forward slash for arguments and backslash for folder boundaries works consistently.

For Example:

xcopy /S /I /D /Y "DRIVE:\Folder1\Folder2" ".\Folder1"

Hope this helps...

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top