Unable to execute child_process.exec() when path has spaces

泄露秘密 提交于 2019-12-10 01:18:08

问题


I am using appjs * and I want to execute a command to open a folder.

What I have

var path = __dirname + '/folder to open/'; 
// path = C:\Program Files\myapplication/folder to open/
require("child_process").exec("start " + path);

Error

Could not find file C:\Program

What I tried

I already tried to escape the spaces, that didn't work.

var path = __dirname + '/folder to open/'; 
path = path.replace(' ', '\ ');
// path = C:\Program Files\myapplication/folder to open/
require("child_process").exec("start " + path);

When I put the path between quotes, No folder is opened, only another prompt.

var path = "\"" + __dirname + "/folder to open/\"";
path = path.replace(' ', '\ ');
// path = "C:\Program Files\myapplication/folder to open/"
require("child_process").exec("start " + path);

Related bug https://github.com/isaacs/npm/pull/2479

Does anyone has a fix or a workaround?

* link removed


回答1:


To open a path than contains spaces, you must replace with a double backslash.

In your code you escaped the space character:

"\ "

What you need to do is escape the backslash character so it makes it into the output string:

"\\ "

Try this:

var path = __dirname + '/folder to open/'; 

// Notice the double-backslashes on this following line
path = path.replace(/ /g, '\\ ');

require("child_process").exec("start " + path);



回答2:


Well, I fixed it.

Or something like it.

Instead of using

"start " + path

I used

"%SystemRoot%\\explorer.exe \"" + path + "\""

Notice the quotes and the forward slashes.




回答3:


this works for me

f= file.replace(/ /g,"\\\ ")


来源:https://stackoverflow.com/questions/16395612/unable-to-execute-child-process-exec-when-path-has-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!