如何从Node.js内部正确执行cd命令? [英] How to correctly execute the cd command from inside of Node.js?

查看:919
本文介绍了如何从Node.js内部正确执行cd命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个非常简单的Windows电子应用程序,当从命令提示符处执行该应用程序时,它会打开一个对话框,用户可以选择一个文件夹。然后,应用程序会将命令提示符目录更改为用户选择的目录。

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.

我的最终目标是能够简单地键入 dirnav ,从对话框中选择一个文件夹,让应用程序负责将命令提示符重定向到所选目录(而不是键入 cd C:\Users\myName\到目前为止,这是我所拥有的:

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();
            });
        }
    );
});

不幸的是,仅仅执行 exec('cd'+ response [0])似乎不起作用,因为而不是更改应用程序运行所在的命令提示符的目录,而是更改另一个(我不知道)命令提示符的目录。有什么办法解决这个问题?

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?

推荐答案

这里有一个简单的方案可以在批处理文件中使用:

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%

然后,我的yourapp.js就是这个(只是为了证明这个概念有效):

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

您应该可以插入在您自己的应用程序的电子 showOpenDialog()中,然后将结果写入 process.stdout

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

批处理文件中的 for 循环确实看起来很奇怪,但这是我发现人们发现得到的唯一途径从应用程序到环境变量的标准输出,您以后可以在批处理文件中使用它。当然,您也可以使用临时文件(将输出重定向到临时文件),但是我认为环境变量是一种更清洁的解决方案。

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.

这篇关于如何从Node.js内部正确执行cd命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆