Advertisement
Guest User

GetMasterLocales

a guest
Nov 22nd, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs');
  2. const path = require('path');
  3.  
  4. const jsonFilePaths = [
  5.   ...searchRecursive('../../features'), // Change me
  6.   ...searchRecursive('../../screens'), // Change me
  7. ]
  8.  
  9. const master = jsonFilePaths.reduce((acc, cur) => {
  10.   const [filename/*unused*/, path] = cur;
  11.   const contents = require(path);
  12.   Object.entries(contents).forEach(([key, val]) => {
  13.     if (key in acc) {
  14.       acc[key] = (Array.isArray(acc[key]))
  15.         ? [...acc[key], ...val]
  16.         : {...acc[key], ...val};
  17.     } else {
  18.       acc[key] = val;
  19.     }
  20.   })
  21.   return acc;
  22. }, {})
  23.  
  24. fs.writeFile(
  25.   './languages/masterTranslations.json',  // This is where the file will be stored. Change me if you want.
  26.   JSON.stringify(master),
  27.   (error) => { if (error) console.log(error); }
  28. );
  29.  
  30. /**
  31.  * Recursively searches sub directories and files for json files and collects their filenames and paths
  32.  *
  33.  * @param {string} dir - directory to look for json files
  34.  * @returns {Array<object>} results: [{name: path}]
  35.  */
  36. function searchRecursive(dir) {
  37.   // This is where we store pattern matches of all files inside the directory
  38.   let results = [];
  39.   // Read contents of directory
  40.   fs.readdirSync(dir).forEach(function(dirInner) {
  41.     const _dirInner = path.resolve(dir, dirInner);
  42.     const stat = fs.statSync(_dirInner);
  43.     // If path is a directory, scan it and combine results
  44.     if (stat.isDirectory()) {
  45.       results = results.concat(searchRecursive(_dirInner));
  46.     }
  47.     // If path is a file and ends with pattern then push it onto results
  48.     if (stat.isFile() && dirInner.endsWith('.json')) {
  49.       const fileName = _dirInner.slice(_dirInner.lastIndexOf('/') + 1).split('.json')[0];
  50.       results.push([fileName, _dirInner]);
  51.     }
  52.   });
  53.   return results;
  54. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement