Skip to content

Instantly share code, notes, and snippets.

@nissoh
Forked from anaisbetts/example.js
Created January 15, 2016 10:17
Show Gist options
  • Save nissoh/43bf4193d71cc18293bc to your computer and use it in GitHub Desktop.
Save nissoh/43bf4193d71cc18293bc to your computer and use it in GitHub Desktop.
Cool tricks with ES6 templated strings
import {p} from './get-path';
console.log(p`${'userDesktop'}/MyApp`);
// On Windows
>> C:\Users\TheUser\Desktop\MyApp
// On OS X
>> /Users/TheUser/Desktop/MyApp
console.log(p`${'HOME'}/Downloads`)
// On Windows
>> C:\Users\TheUser\Downloads
// On OS X
>> /Users/TheUser/Downloads
import _ from 'lodash';
import path from 'path';
let electronApp = null;
if (process.type === 'renderer') {
electronApp = require('remote').require('app');
} else {
electronApp = require('app');
}
// NB: Some environment variables are known to app.getPath and we don't have
// to worry about them disappearing on us. Use them instead.
const environmentVariableAliases = {
'HOME': 'home',
'USERPROFILE': 'home',
'APPDATA': 'appData',
'TEMP': 'temp',
'TMPDIR': 'temp'
};
const pathCache = { };
export function getPath(key) {
if (pathCache[key]) return pathCache[key];
let aliasKey = null;
if (environmentVariableAliases[key]) {
aliasKey = environmentVariableAliases[key];
}
let result = null;
try {
result = electronApp.getPath(aliasKey || key);
} catch (e) {
console.log(e);
}
result = result || process.env[key];
if (!result) {
// NB: Try to fix up the most commonly fucked environment variables
if (key.toLowerCase() === 'appdata' && process.env.USERPROFILE) {
result = path.join(process.env.USERPROFILE, 'AppData', 'Roaming');
}
if (key.toLowerCase() === 'localappdata' && process.env.USERPROFILE) {
result = path.join(process.env.USERPROFILE, 'AppData', 'Local');
}
}
if (result) pathCache[key] = result;
return result;
}
export function p(strings, ...values) {
let newVals = _.map(values, (x) => getPath(x));
let newPath = String.raw(strings, ...newVals);
let parts = _.map(newPath.split(/[\\\/]/), (x) => x || '/');
try {
return path.resolve(...parts);
} catch (e) {
return path.join(...parts);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment