Removing spaces in the file path

I am wondering how I can programmatically add \ in front of the spaces that appear in the file path. I use fs.readdir to get the contents of directories, and if I don't get out of the spaces from the path, I get an ENOENT error message because unescaped paths are not allowed on UNIX. I would like to get the result:

 /path/with\ spaces/in/them/ 

However, I ran into a problem with REGEX in the NODE REPL. When I do this:

 var path = '/path/with spaces/in/them/'; var escapedPath = path.replace(/(\s)/, "\\ "); 

I get the result:

 '/path/with\\ spaces/in/them/' 

When I try to run the same code inside the Chrome console, I get:

 "/path/with\ spaces/in/them/" 

What is the desired effect.

I'm not sure if I missed something or if this is a mistake. I am confused because NODE runs on the same Javascript engine as Chrome, so I think these expressions will be interpreted the same way.

Please let me know if anyone knows a way around this. Maybe I'm missing something. I just need to get away from the paths before passing them to fs.readdir so that I can avoid these errors.

Thanks!

+6
source share
2 answers

fs.readdir does not require path removal. I was able to fs.readdir output directories back to fs.readdir without any problems.

The problem above with REGEX only occurs in Node REPL. As soon as I tested the above code inside the file, I was able to run it through Node and get the same result that I saw in the Chrome console.

As a result, I found an error in my code that was difficult to track. At first I thought that this was due to the fact that he did not slip the path that I sent to fs.readdir , but actually it was a problem when I had fs.stat output fs.readdir , and then checked. whether the output was a file or a directory it accordingly.

It turned out that several of the stat results were neither files nor directories, and my function had no way to handle this, so it just came back. Since I had no handlers, my Node program just stopped. All I had to do was add an extra else clause to catch cases without files / directories (which I don't like anyway).

Now it works great!

+2
source

try either this

 var path = "'file:///Users/kevin/folder with space'"; 

or

 var path = "\"file:///Users/kevin/folder with space\""; 
0
source

Source: https://habr.com/ru/post/950733/


All Articles