Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a directory in File Explorer

On ms Windows from node.js code, how can I open a specific directory (ex: c:\documents) in Windows file explorer?

I guess in c#, it would be:

process.Start(@"c:\test")
like image 420
Abdullah Avatar asked Jan 28 '16 21:01

Abdullah


People also ask

Where is the directory in File Explorer?

This button can be found in the lower-left corner of the screen, and may just be a Windows logo. Click the Computer or File Explorer button. In Windows 10, this looks like a folder and can be found on the left side of the menu, or in your Windows task bar at the bottom of the screen.


2 Answers

Try the following, which opens a File Explorer window on the computer running Node.js:

require('child_process').exec('start "" "c:\\test"');

If your path doesn't contain whitespace, you can also get away with 'start c:\\test', but the above - which requires "" as the 2nd argument[1] is the most robust approach.

Note:

  • The File Explorer window will launch asynchronously, and will receive focus when it does.

  • This related question asks for a solution that prevents the window from "stealing" focus.


[1] cmd.exe's internal start command by default interprets a "..."-enclosed 1st argument as the window title for the new console window to create (which doesn't apply here). By supplying a (dummy) window title - "" - explicitly, the 2nd argument is reliably interpreted as the target executable / document path.

like image 104
mklement0 Avatar answered Sep 25 '22 07:09

mklement0


I found another way on the WSL and potentially windows itself.

Note that you have to make sure you're formatting the path for Windows not Linux (WSL). I wanted to save something on Windows, so in order to do that you use /mnt directory on WSL.

// format the path, so Windows isn't mad at us
// first we specify that we want the path to be compatible with windows style
// then we replace the /mnt/c/ with the format that windows explorer accepts
// the path would look like `c:\\Users\some\folder` after this line
const winPath = path.win32.resolve(dir).replace('\\mnt\\c\\', 'c:\\\\');

// then we use the same logic as the previous answer but change it up a bit
// do remember about the "" if you have spaces in your name
require('child_process').exec(`explorer.exe "${winPath}"`);

This should open the file explorer for you.

like image 32
ohaleks Avatar answered Sep 24 '22 07:09

ohaleks