UNPKG

@mediafly/translate

Version:

Translate strings extracted from apps using Google Translate

65 lines (48 loc) 1.55 kB
const path = require('path') const fs = require('fs') const iso = require('iso-639-1') const countryList = require('iso-3166-country-list') const _ = require('lodash') const config = require(path.join(process.cwd(), 'mediafly-translate.config')) exports.requireOrDefault = (filePath, defaultValue = {}) => { var jsonFile = _.attempt(() => { return require(path.resolve(filePath)) }) if (_.isError(jsonFile)) { jsonFile = defaultValue } return jsonFile } exports.getLanguageName = (code) => { let parts = code.split('-') let languageCode = parts[0] let languageName = iso.getName(languageCode) let countryName = '' if (parts.length > 1) { countryName = countryList.name(parts[1]) } if (countryName) { return `${languageName} (${countryName})` } else { return languageName } } /** * Returns the value of the `translationsDir` config key in `mediafly-translate.config.json`. * `translationsDir` should be a relative path like `./src/translations`. * If that key doesn't exist, the default value is `/translations` inside the current working directory. */ exports.getTranslationsDir = () => { const configDir = config.translationsDir if (!configDir) { return path.join(process.cwd(), 'translations') } // statSync checks if the path exists and insures it's a directory, it throws if not (but with a worse error message). try { fs.statSync(configDir) } catch { throw new Error(`The translationsDir path specified in mediafly-translate.config doesn't exist: ${configDir}`) } return configDir }