I am wondering how I can programmatically add \
in front of spaces that appear in file paths. I am using fs.readdir
to get the contents of directories and if I don't escape the spaces out of the path then I get an ENOENT
error because unescaped paths are invalid in UNIX. I'd like get below result :
/path/with\ spaces/in/them/
However, I am running into a problem with a REGEX in the NODE REPL. When I do :
var path = '/path/with spaces/in/them/';
var escapedPath = path.replace(/(\s)/, "\\ ");
I get as result :
'/path/with\\ spaces/in/them/'
When I try to run this same code inside of the Chrome console I get :
"/path/with\ spaces/in/them/"
Which is the desired effect.
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.
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 fs.readdir
so that I can avoid these errors.
Thanks!
fs.readdir
doesn't require you to escape paths. I was able to recursively pass fs.readdir
output directories back into fs.readdir
without any issues.
The issue above with the REGEX was only occuring in the Node REPL. Once I tested the above code inside of a file I was able to run it through Node and get the same output I saw in the Chrome console.
I ended up finding a bug in my code that was a little hard to track down. I first thought that it came from not escaping the path I was sending into fs.readdir
but it was actually an issue where I was fs.stat
the output of fs.readdir
and then checking if the output was a file or a directory and treating it accordingly.
It turns out that a few results from the stat were neither Files or Directories and my function didn't have any way to deal with this so it just returned. Since I had no handlers for this my node program just stopped abrubtly. All I had to do was add an extra else
condition to catch the non-file/directories cases (which I don't care about anyway).
Now its working fine!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With