【问题标题】:How can I get the path that the application is running with typescript?如何获取应用程序使用 typescript 运行的路径?
【发布时间】:2016-09-09 20:50:57
【问题描述】:

我正在尝试使用 electron、angular2、typescript 和 neDB 创建一个桌面应用程序。为了能够使用 neDB 创建一个“文件”数据库,我想要我的项目的路径。我如何使用 typescript 获得这个?

【问题讨论】:

    标签: typescript electron nedb


    【解决方案1】:

    使用app.getAppPath()

    Typescript 是 javascript 的超集,因此您可以像使用 javascript 一样执行此操作,但您可能希望声明类型,或在这样做时使用其他 typescript 功能。

    例子:

    const remote = require('remote'), 
          app = remote.require('app');
    
    var basepath = app.getAppPath();
    

    更新 - 这些天你应该使用:

    const app = require('electron').remote.app
    

    获取app.getAppPath() 的应用句柄。

    【讨论】:

    • 在新版本的电子中,应该使用require('electron').remote.app
    • 对于更新版本的电子,应该使用require('electron').app
    • @Fergal 使用5.0.6 我使用require('electron').app 得到一个空值,而require('electron').remote.app 返回正确的引用
    • 在 2020 年它被进一步截断为 require('electron').app.getAppPath();
    【解决方案2】:

    将数据写入应用程序安装目录通常不是一个好主意,因为运行应用程序的用户可能无权将文件写入该目录。您可能应该做的是在app.getPath('userData') 返回的位置创建数据库文件。

    【讨论】:

    • 除非是便携应用
    • @Vadim Macagon,我在 main.js 中定义了app = require('electron'),然后在另一个文件中尝试使用 app.getPath('userData')。它显示为未定义,我认为这是因为 app 只能有一个实例。有解决办法吗?
    【解决方案3】:

    如果您正在运行打包的应用程序并且您想要获取应用程序可执行文件的路径(不是主节点进程索引脚本路径,可能在 ASAR 中),app.getAppPath() 不正确。你想要app.getPath("exe"),并得到它的路径:

    require("path").dirname(require('electron').remote.app.getPath("exe"))
    

    【讨论】:

    • 对于较新的电子版本,请使用require("path").dirname(require('electron').app.getPath("exe"))
    【解决方案4】:

    这对我有用:

    require('electron').remote.app.getAppPath()
    

    【讨论】:

      【解决方案5】:

      如果这对某人有帮助,我已经下载了 npm 包 electron-root-path,它在我的情况下完美运行。

      // Import ES6 way
      import { rootPath } from 'electron-root-path';
       
      // Import ES5 way
      const rootPath = require('electron-root-path').rootPath;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-25
        • 1970-01-01
        • 2012-07-05
        相关资源
        最近更新 更多