How to correctly execute the cd command from inside of Node.js?

北城以北 提交于 2020-01-07 08:13:40

问题


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?


回答1:


Here's a simple scheme that will work from a batch file:

for /f %%i in ('node yourapp.js') do set NEWDIR=%%i
cd %NEWDIR%

And, my yourapp.js is this (just to prove that the concept works):

process.stdout.write("subdir");

This will end up executing in the batch file:

cd subdir

You should be able to plug in your electron showOpenDialog() in your own app and then just write the result to process.stdout.

The for loop in the batch file does indeed look odd, but it's the only way I found that people have found to get the stdout from an app into an environment variable that you can then use later in the batch file. You could, of course also use a temp file (redirect output to a temp file), but I thought an environment variable was a cleaner solution.



来源:https://stackoverflow.com/questions/51228181/how-to-correctly-execute-the-cd-command-from-inside-of-node-js

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