當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript app.getPath方法代碼示例

本文整理匯總了TypeScript中electron.app.getPath方法的典型用法代碼示例。如果您正苦於以下問題:TypeScript app.getPath方法的具體用法?TypeScript app.getPath怎麽用?TypeScript app.getPath使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在electron.app的用法示例。


在下文中一共展示了app.getPath方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: catch

import ospath from "path";
import fs from "fs";
import { app } from "electron";

import logger from "common/logger";

let configFile = ospath.join(app.getPath("userData"), "config.json");
let data: any = {};

try {
  data = JSON.parse(fs.readFileSync(configFile, { encoding: "utf8" }));
} catch (e) {
  // We don't want that to be fatal
  if (e.code === "ENOENT") {
    // that's ok
    logger.info("No config file, it's a fresh install!");
  } else {
    logger.warn(`Could not read config: ${e}`);
  }
}

const self = {
  save: function() {
    try {
      fs.writeFileSync(configFile, JSON.stringify(data), { encoding: "utf8" });
    } catch (err) {
      logger.warn(`Could not save config: ${err}`);
    }
  },

  get: function(key: string): any {
開發者ID:HorrerGames,項目名稱:itch,代碼行數:31,代碼來源:config.ts

示例2: getSettingsFilePath

function getSettingsFilePath() {
    return app.getPath("userData") + "/" + SETTINGS_FILE_NAME;
}
開發者ID:eez-open,項目名稱:studio,代碼行數:3,代碼來源:settings.ts

示例3: readBracketsPreferences

export function readBracketsPreferences() {
    const dirPath = app.getPath("userData");
    const defaultPreferences = tryReadJson(path.resolve(dirPath, DEFAULT_PREFERENCES_FILENAME));
    const currentPreferences = tryReadJson(path.resolve(dirPath, CURRENT_PREFERENCES_FILENAME));
    return _.defaultsDeep(currentPreferences, defaultPreferences);
}
開發者ID:Real-Currents,項目名稱:brackets,代碼行數:6,代碼來源:brackets-config.ts

示例4: updateWallet

ipcMain.on("nodeInit", () => {
  if (win && win.webContents) {
    win.webContents.send("nodeStatus", nodeStatus);
    win.webContents.send("autoReconnect", autoReconnect);
  }
  if (node) {
    if (win && win.webContents) {
      updateWallet();
      updateSettings();
    }
    return;
  }

  console.log("[NODE]: initializing node...");
  node = new Node({
    userDataPath: app.getPath("userData")
  });

  updateSettings();
  updateWallet();
  refreshBalance();
  node.on("started", () => {
    console.log("[NODE]: started.");
    speedInterval = setInterval(() => {
      if (win && win.webContents) {
        win.webContents.send("downloadSpeed", node.contentsClient.downloadSpeed);
      }
      if (win && win.webContents) {
        win.webContents.send("uploadSpeed", node.contentsClient.uploadSpeed);
      }
    }, 250);
  });
  node.master.on("connected", () => {
    updateNodeStatus("running");
    console.log("[NODE]: connected to master.");
  });
  node.master.on("closed", info => {
    if (info && info.code !== 1000) {
      if (info && info.code === 1002) {
        console.log(`[NODE]: connection with master closed, info =`, info);
        if (win && win.webContents) {
          win.webContents.send("alertError", info.reason);
        }
      }
      checkInternet(isConnected => {
        const isConnectedPrefix = isConnected ? "" : "No internet connection, please connect to the internet. ";
        console.log(`[NODE]: connection with master closed, info =`, info);
        if (win && win.webContents) {
          win.webContents.send("autoReconnect", autoReconnect);
        }
        const seconds = 60;
        if (autoReconnect) {
          secondsLeft = seconds;
          if (autoReconnectInterval) {
            clearTimeout(autoReconnectInterval);
          }

          autoReconnectInterval = setInterval(() => {
            secondsLeft -= 1;
            if (secondsLeft <= 0) {
              nodeStart();
            }
            updateNodeStatus("reconnecting", secondsLeft);
          }, 1 * 1000);
        }
        const autoReconnectPostfix = autoReconnect ? `, will try to reconnect in  ${seconds} seconds` : "";
        if (win && win.webContents) {
          win.webContents.send("alertError", `${isConnectedPrefix}Failed to connect to master${autoReconnectPostfix}`);
        }
      });
      node.stop();
    } else {
      console.log(`[NODE]: connection with master closed, normal exit`);
    }
  });
  ipcMain.on("setAutoReconnect", (sender, isAutoReconnect) => {
    autoReconnect = isAutoReconnect;
  });
  node.master.on("cache", info => {
    console.log(`[NODE][IN]: cache request, resource = ${info.source.url}`);
  });
  node.master.on("clear", info => {
    console.log(`[NODE][IN]: clear request, infoHashes = ${info.infoHashes}`);
  });
  node.master.on("seed", info => {
    console.log("[NODE][IN]: seed request.");
  });
  if (node.clientSockets.http) {
    node.clientSockets.http.on("listening", info => {
      console.log(`[NODE]: listening for HTTP requests on port ${info.port}.`);
    });
  }
  if (node.clientSockets.ws) {
    node.clientSockets.ws.on("listening", info => {
      console.log(`[NODE]: listening for ${info.ssl ? "WSS" : "WS"} requests on port ${info.port}.`);
    });
    node.clientSockets.ws.on("connections", count => {
      console.log(`[NODE]: WS Clients connections = ${count}`);
      if (win && win.webContents) {
        win.webContents.send("connections", count);
//.........這裏部分代碼省略.........
開發者ID:stargeizer,項目名稱:noia-node-gui,代碼行數:101,代碼來源:main.ts

示例5: function

 mainWindow.webContents.on('did-finish-load', function () {
     mainWindow.webContents.send('scheduler-load', app.getPath('userData'), 'schedules-main.json');
     mainWindow.webContents.send('scheduler-tray-click', 'hey!');
 });
開發者ID:frieck,項目名稱:WiN,代碼行數:4,代碼來源:desktop.ts

示例6: CustomProtocolHandler

import {TrayHandler} from './menu/TrayHandler';
import * as EnvironmentUtil from './runtime/EnvironmentUtil';
import * as lifecycle from './runtime/lifecycle';
import {OriginValidator} from './runtime/OriginValidator';
import * as config from './settings/config';
import {settings} from './settings/ConfigurationPersistence';
import {SettingsType} from './settings/SettingsType';
import {SingleSignOn} from './sso/SingleSignOn';
import {AboutWindow} from './window/AboutWindow';
import {WindowManager} from './window/WindowManager';
import {WindowUtil} from './window/WindowUtil';

// Paths
const APP_PATH = app.getAppPath();
const INDEX_HTML = path.join(APP_PATH, 'renderer/index.html');
const LOG_DIR = path.join(app.getPath('userData'), 'logs');
const LOG_FILE = path.join(LOG_DIR, 'electron.log');
const PRELOAD_JS = path.join(APP_PATH, 'dist/renderer/preload.js');
const PRELOAD_RENDERER_JS = path.join(APP_PATH, 'renderer/static/webview-preload.js');
const WRAPPER_CSS = path.join(APP_PATH, 'css/wrapper.css');
const WINDOW_SIZE = {
  DEFAULT_HEIGHT: 768,
  DEFAULT_WIDTH: 1024,
  MIN_HEIGHT: 512,
  MIN_WIDTH: 760,
};

const logger = LogFactory.getLogger(__filename, {forceEnable: true, logFilePath: LOG_FILE});
const customProtocolHandler = new CustomProtocolHandler();

// Config
開發者ID:wireapp,項目名稱:wire-desktop,代碼行數:31,代碼來源:main.ts

示例7: async

  watcher.on(actions.preboot, async (store, action) => {
    let t1 = Date.now();
    try {
      const system: SystemState = {
        appName: app.getName(),
        appVersion: app.getVersion().replace(/\-.*$/, ""),
        platform: itchPlatform(),
        arch: arch(),
        macos: process.platform === "darwin",
        windows: process.platform === "win32",
        linux: process.platform === "linux",
        sniffedLanguage: app.getLocale(),
        homePath: app.getPath("home"),
        userDataPath: app.getPath("userData"),
        proxy: null,
        proxySource: null,
        quitting: false,
      };
      store.dispatch(actions.systemAssessed({ system }));

      try {
        await loadPreferences(store);
      } catch (e) {
        logger.error(
          `Could not load preferences: ${e.stack || e.message || e}`
        );
      }

      try {
        const netSession = session.fromPartition(NET_PARTITION_NAME, {
          cache: false,
        });

        const envSettings: string =
          process.env.https_proxy ||
          process.env.HTTPS_PROXY ||
          process.env.http_proxy ||
          process.env.HTTP_PROXY;

        let proxySettings = {
          proxy: null as string,
          source: "os" as ProxySource,
        };

        if (envSettings) {
          logger.info(`Got proxy settings from environment: ${envSettings}`);
          proxySettings = {
            proxy: envSettings,
            source: "env",
          };
          testProxy = true;
          store.dispatch(actions.proxySettingsDetected(proxySettings));
        }
        await applyProxySettings(netSession, proxySettings);
      } catch (e) {
        logger.warn(
          `Could not detect proxy settings: ${e ? e.message : "unknown error"}`
        );
      }

      if (env.production && env.appName === "itch") {
        try {
          app.setAsDefaultProtocolClient("itchio");
          app.setAsDefaultProtocolClient("itch");
        } catch (e) {
          logger.error(
            `Could not set app as default protocol client: ${e.stack ||
              e.message ||
              e}`
          );
        }
      }
    } catch (e) {
      throw e;
    } finally {
      const t2 = Date.now();
      logger.info(`preboot ran in ${elapsed(t1, t2)}`);
    }

    store.dispatch(actions.prebootDone({}));

    let devtoolsPath = process.env.ITCH_REACT_DEVTOOLS_PATH;
    if (!devtoolsPath && env.development) {
      let reactDevtoolsId = "fmkadmapgofadopljbjfkapdkoienihi";
      let devtoolsFolder = path.join(
        app.getPath("home"),
        "AppData",
        "Local",
        "Google",
        "Chrome",
        "User Data",
        "Default",
        "Extensions",
        reactDevtoolsId
      );
      try {
        const files = fs.readdirSync(devtoolsFolder);
        let version = files[0];
        if (version) {
          devtoolsPath = path.join(devtoolsFolder, version);
//.........這裏部分代碼省略.........
開發者ID:itchio,項目名稱:itch,代碼行數:101,代碼來源:preboot.ts

示例8: expect

 expect(() => { app.getPath(badPath) }).to.throw()
開發者ID:electron,項目名稱:electron,代碼行數:1,代碼來源:api-app-spec.ts

示例9: constructor

	constructor() {
		this._appRoot = path.dirname(URI.parse(require.toUrl('')).fsPath);
		this._currentWorkingDirectory = process.env['VSCODE_CWD'] || process.cwd();
		this._appHome = app.getPath('userData');
		this._appSettingsHome = path.join(this._appHome, 'User');
		this._appSettingsPath = path.join(this._appSettingsHome, 'settings.json');
		this._appKeybindingsPath = path.join(this._appSettingsHome, 'keybindings.json');

		// Remove the Electron executable
		let [, ...args] = process.argv;

		// If dev, remove the first non-option argument: it's the app location
		if (!this.isBuilt) {
			const index = arrays.firstIndex(args, a => !/^-/.test(a));

			if (index > -1) {
				args.splice(index, 1);
			}
		}

		// Finally, prepend any extra arguments from the 'argv' file
		if (fs.existsSync(path.join(this._appRoot, 'argv'))) {
			const extraargs: string[] = JSON.parse(fs.readFileSync(path.join(this._appRoot, 'argv'), 'utf8'));
			args = [...extraargs, ...args];
		}

		const argv = parseArgs(args);

		const debugBrkExtensionHostPort = getNumericValue(argv.debugBrkPluginHost, 5870);
		const debugExtensionHostPort = getNumericValue(argv.debugPluginHost, 5870, this.isBuilt ? void 0 : 5870);
		const pathArguments = parsePathArguments(this._currentWorkingDirectory, argv._, argv.goto);
		const timestamp = parseInt(argv.timestamp);
		const debugBrkFileWatcherPort = getNumericValue(argv.debugBrkFileWatcherPort, void 0);

		this._cliArgs = Object.freeze({
			pathArguments: pathArguments,
			programStart: types.isNumber(timestamp) ? timestamp : 0,
			enablePerformance: argv.performance,
			verboseLogging: argv.verbose,
			debugExtensionHostPort: debugBrkExtensionHostPort || debugExtensionHostPort,
			debugBrkExtensionHost: !!debugBrkExtensionHostPort,
			logExtensionHostCommunication: argv.logExtensionHostCommunication,
			debugBrkFileWatcherPort: debugBrkFileWatcherPort,
			openNewWindow: argv['new-window'],
			openInSameWindow: argv['reuse-window'],
			gotoLineMode: argv.goto,
			diffMode: argv.diff && pathArguments.length === 2,
			extensionsHomePath: normalizePath(argv.extensionHomePath),
			extensionDevelopmentPath: normalizePath(argv.extensionDevelopmentPath),
			extensionTestsPath: normalizePath(argv.extensionTestsPath),
			disableExtensions: argv['disable-extensions'],
			locale: argv.locale,
			waitForWindowClose: argv.wait
		});

		this._isTestingFromCli = this.cliArgs.extensionTestsPath && !this.cliArgs.debugBrkExtensionHost;
		this._userHome = path.join(os.homedir(), product.dataFolderName);
		this._userExtensionsHome = this.cliArgs.extensionsHomePath || path.join(this._userHome, 'extensions');

		const prefix = this.getIPCHandleBaseName();
		const suffix = process.platform === 'win32' ? '-sock' : '.sock';

		this._mainIPCHandle = `${ prefix }-${ pkg.version }${ suffix }`;
		this._sharedIPCHandle = `${ prefix }-${ pkg.version }-shared${ suffix }`;
	}
開發者ID:Joanlove526,項目名稱:vscode,代碼行數:65,代碼來源:env.ts

示例10: require

import { app } from "electron";
const ua = require("universal-analytics");
const uuid = require("uuid/v4");
const { JSONStorage } = require("node-localstorage");
const nodeStorage = new JSONStorage(app.getPath("userData"));

// Retrieve the userId value, and if it's not there, assign it a new uuid.
const userId = nodeStorage.getItem("userId") || uuid();
nodeStorage.setItem("userId", userId);

const usr = ua("UA-101346362-5", userId);

export default function trackEvent(
	category: string,
	action: string,
	label?: string,
	value?: any,
) {
	usr.event({
		ec: category,
		ea: action,
		el: label,
		ev: value,
	}).send();
}

export function exceptionEvent(desc: string, fatal?: boolean) {
	usr.exception(desc, fatal);
}

export function timingEvent(category: string, variable: string, time: number) {
開發者ID:ellcrys,項目名稱:safehold,代碼行數:31,代碼來源:analytics.ts

示例11: function

/* const watchClient = new Client();
watchClient.capabilityCheck({ optional: [], required: ['relative_root'] },
function (error, resp) {
    if (error) {
        // error will be an Error object if the watchman service is not
        // installed, or if any of the names listed in the `required`
        // array are not supported by the server
        console.error(error);
    }
    // resp will be an extended version response:
    // {'version': '3.8.0', 'capabilities': {'relative_root': true}}
    console.log(resp);
});*/

let mainWindow: BrowserWindow | null;
const appFolderPath = join(app.getPath('appData'), 'CopyCat');
const settingsFile = join(appFolderPath, 'state.json');
const DEV_MODE = true;

if (!existsSync(appFolderPath)) {
    mkdirSync(appFolderPath);
}

if (!existsSync(settingsFile)) {
    writeFileSync(settingsFile, '{}');
}

if (DEV_MODE) {
    app.setName('CopyCat');
}
開發者ID:istvan-antal,項目名稱:copycat,代碼行數:30,代碼來源:main.ts

示例12: setApplicationMenu

// in config/env_xxx.json file.
import env from './env';

const setApplicationMenu = () => {
  const menus = [editMenuTemplate];
  if (env.name !== 'production') {
    menus.push(devMenuTemplate);
  }
  Menu.setApplicationMenu(Menu.buildFromTemplate(menus));
};

// Save userData in separate folders for each environment.
// Thanks to this you can use production and development versions of the app
// on same machine like those are two separate apps.
if (env.name !== 'production') {
  const userDataPath = app.getPath('userData');
  app.setPath('userData', `${userDataPath} (${env.name})`);
}

app.on('ready', () => {
  setApplicationMenu();

  const mainWindow = createWindow('main', {
    width: 1000,
    height: 600,
  });

//setTimeout(() => {
    mainWindow.loadURL('file://' + __dirname + '/app.html');
//}, 2000); // 1 second wasn't enough lol
開發者ID:Dorokhov,項目名稱:azure-tools,代碼行數:30,代碼來源:background.ts

示例13: directory

 public static get directory(): string
 {
     return app.getPath("appData") + "/luna";
 }
開發者ID:Kelmar,項目名稱:LunaIRC,代碼行數:4,代碼來源:config.ts

示例14: updateMenu


//.........這裏部分代碼省略.........
	];

	const privacySubmenu: MenuItemConstructorOptions[] = [
		{
			label: 'Block Seen Indicator',
			type: 'checkbox',
			checked: config.get('block.chatSeen'),
			click(menuItem) {
				config.set('block.chatSeen', menuItem.checked);
			}
		},
		{
			label: 'Block Typing Indicator',
			type: 'checkbox',
			checked: config.get('block.typingIndicator'),
			click(menuItem) {
				config.set('block.typingIndicator', menuItem.checked);
			}
		},
		{
			label: 'Block Delivery Receipts',
			type: 'checkbox',
			checked: config.get('block.deliveryReceipt'),
			click(menuItem) {
				config.set('block.deliveryReceipt', menuItem.checked);
			}
		}
	];

	const advancedSubmenu: MenuItemConstructorOptions[] = [
		{
			label: 'Custom Styles',
			click() {
				const filePath = path.join(app.getPath('userData'), 'custom.css');
				const defaultCustomStyle = `/*
This is the custom styles file where you can add anything you want.
The styles here will be injected into Caprine and will override default styles.
If you want to disable styles but keep the config, just comment the lines that you don't want to be used.

Here are some dark mode color variables to get you started.
Edit them to change color scheme of Caprine.
Press Command/Ctrl+R in Caprine to see your changes.
*/

:root {
	--base: #000;
	--base-ninety: rgba(255, 255, 255, 0.9);
	--base-seventy-five: rgba(255, 255, 255, 0.75);
	--base-seventy: rgba(255, 255, 255, 0.7);
	--base-fifty: rgba(255, 255, 255, 0.5);
	--base-fourty: rgba(255, 255, 255, 0.4);
	--base-thirty: rgba(255, 255, 255, 0.3);
	--base-twenty: rgba(255, 255, 255, 0.2);
	--base-five: rgba(255, 255, 255, 0.05);
	--base-ten: rgba(255, 255, 255, 0.1);
	--base-nine: rgba(255, 255, 255, 0.09);
	--container-color: #323232;
	--container-dark-color: #1e1e1e;
	--list-header-color: #222;
	--blue: #0084ff;
	--selected-conversation-background: linear-gradient(hsla(209, 110%, 45%, 0.9), hsla(209, 110%, 42%, 0.9));
}
`;

				if (!existsSync(filePath)) {
					writeFileSync(filePath, defaultCustomStyle, 'utf8');
開發者ID:kusamakura,項目名稱:caprine,代碼行數:67,代碼來源:menu.ts

示例15: expect

 expect(() => {
   app.getPath('does-not-exist')
 }).to.throw(/Failed to get 'does-not-exist' path/)
開發者ID:doridoridoriand,項目名稱:electron,代碼行數:3,代碼來源:api-app-spec.ts


注:本文中的electron.app.getPath方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。