本文整理汇总了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 {
示例2: getSettingsFilePath
function getSettingsFilePath() {
return app.getPath("userData") + "/" + SETTINGS_FILE_NAME;
}
示例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);
}
示例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);
//.........这里部分代码省略.........
示例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!');
});
示例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
示例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);
//.........这里部分代码省略.........
示例8: expect
expect(() => { app.getPath(badPath) }).to.throw()
示例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 }`;
}
示例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) {
示例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');
}
示例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
示例13: directory
public static get directory(): string
{
return app.getPath("appData") + "/luna";
}
示例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');
示例15: expect
expect(() => {
app.getPath('does-not-exist')
}).to.throw(/Failed to get 'does-not-exist' path/)