I'm developing a very simple Electron app for Windows which, when executed from the command prompt, opens a dialog box trough which the user can select a folder. The app would then change the command prompt directory to the directory selected by the user.
My end goal is to be able to simply type dirnav, select a folder from the dialog box and have the app take care of redirecting the command prompt to the selected directory (instead of typing cd C:\Users\myName\whateverDirectory. Here's what I have so far:
const exec = require('child_process').exec;
const electron = require('electron');
const {app, dialog} = electron;
app.on('ready', () => {
dialog.showOpenDialog(
{
title: 'Select a directory',
defaultPath: '.',
buttonLabel: 'Select',
properties: ['openDirectory']
}, (responce) => {
exec('cd ' + responce[0], () => {
app.quit();
});
}
);
});
Unfortunately, simply doing exec('cd ' + responce[0]) doesn't seem to work, because instead of changing the directory of the command prompt the application was runned from, it changes the directory of another (unknown to me) command prompt. Is there any way to work around that?
exec()it makes a new command prompt that has it's entirely own environment. As you have discovered, changing the directory in that and then letting that shell window exit just changes the current directory in that shell prompt and does not affect anything else.cd.exe, try runningwhere cdand see. That's because a process can only change it's environment, and the changes will be lost when it exits. Thereforecdhas to be an internal command. Same in *nixcd.exe.cdis an internal command ofcmd.exe, just asdir,clsandechoare internal tocmd.exe.. In addition,cdonly affects the currently open command (terminal) window, and what your code is doing doesn't make much sense callingcd.