4
var exec = require('child_process').exec
var cmd = 'C:\\Users\\Johnny Cash\\Desktop\\executeme.exe'

exec(cmd, function(e, stdout, stderr) {
  console.log(e);
  console.log(stdout);
  console.log(stderr);
});

'C:\Users\Johnny' is not recognized as an internal or external command

This has got to be the newbiest question ever, but how do I escape these paths with spaces on windows? It's cuts off at the space and nothing I do (single or double escapes beforehand) seems to do the trick. Does exec() do some formatting I'm not aware of?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
dsp_099
  • 5,801
  • 17
  • 72
  • 128

2 Answers2

10

exec treats any spaces in the command parameter string as argument separators, so you need to double-quote the whole path to have it all treated as the path to the command to run:

var cmd = '"C:\\Users\\Johnny Cash\\Desktop\\executeme.exe"'

But it's probably cleaner just to use execFile instead, as its file parameter is always treated as the file path, with a separate args parameter. Then you should be able to omit the double-quote wrapping. execFile is a bit leaner anyway as it doesn't execute a subshell like exec does.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 1
    What if I need to pass an argument to `exec` which is another long string with spaces? – dsp_099 Aug 28 '15 at 02:10
  • 1
    @dsp_099 Double quote the argument separately or use `execFile` and pass the argument in its own array parameter. – JohnnyHK Aug 28 '15 at 02:15
1

You need to scape the space char from the URI by using ^ (caret) char:

var cmd = 'C:\\Users\\Johnny^ Cash\\Desktop\\executeme.exe'
leo.fcx
  • 6,137
  • 2
  • 21
  • 37
  • This works where everything else fails. We tried double escape. We tried %ProgramFiles% We tried everything we could and every single time we got a "C:\Program" is blabla. BUT THIS. This saved our day. – Quentin Klein Feb 24 '22 at 13:43