user734613
user734613

Reputation:

NodeJS with Child_Process - How to escape my command

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.

Has anyone else got these kind of issues?

Upvotes: 2

Views: 3624

Answers (2)

Milly
Milly

Reputation: 1

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...

Upvotes: -1

robertklep
robertklep

Reputation: 203251

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.

Upvotes: 2

Related Questions