title: Escape spaces in File Path
body: <p>I am wondering how I can programmatically add <code>\</code> in front of spaces that appear in file paths. I am using <code>fs.readdir</code> to get the contents of directories and if I don't escape the spaces out of the path then I get an <code>ENOENT</code> error because unescaped paths are invalid in UNIX. I'd like get below result :</p>
  
  <pre><code>/path/with\ spaces/in/them/
  </code></pre>
  
  <p>However, I am running into a problem with a REGEX in the NODE REPL. When I do :</p>
  
  <pre><code>var path = '/path/with spaces/in/them/';
  var escapedPath = path.replace(/(\s)/, "\\ ");
  </code></pre>
  
  <p>I get as result :</p>
  
  <pre><code>'/path/with\\ spaces/in/them/'
  </code></pre>
  
  <p>When I try to  run this same code inside of the Chrome console I get :</p>
  
  <pre><code>"/path/with\ spaces/in/them/"
  </code></pre>
  
  <p>Which is the desired effect.</p>
  
  <p>I am not sure if I am missing something or if this is a bug. I am confused because Node runs on the same Javascript engine as Chrome so I would think that these expressions would be interpreted the same.</p>
  
  <p>Please let me know if anyone knows a way to do get around this. Maybe I am missing something. I just need to be able to escape the paths before passing them into <code>fs.readdir</code> so that I can avoid these errors.</p>
  
  <p>Thanks!</p>