Skip to content

Instantly share code, notes, and snippets.

@maxmarinich
Created March 30, 2020 09:16
Show Gist options
  • Save maxmarinich/979adcc96a228d90980b0a3953901d8b to your computer and use it in GitHub Desktop.
Save maxmarinich/979adcc96a228d90980b0a3953901d8b to your computer and use it in GitHub Desktop.
Grep any string in NodeJS
const fs = require('fs');
const path = require('path');
const readDir = require('./readDir');
function grepKeys(sourceDir = '', outDir = '') {
const re = /(\$t\(['"]|\$t\(\\['"]|\$t\(\\\\['"])(.*?)(['"]|\\['"]|\\\\['"])/g;
const include = ['.vue', '.ts', 'json', '.js'];
const exclude = ['.Stories.ts', '.stories.ts', '.spec.ts'];
try {
const outputPath = path.join(outDir, 'primary-keys.json');
const files = readDir(sourceDir, { include, exclude, recursive: true });
const keys = files.reduce((acc, item) => {
const file = fs.readFileSync(item, 'utf8');
const [...matches] = file.matchAll(re);
const keys = matches.map((i) => i[2])
acc = acc.concat(keys);
return acc;
}, []);
const result = [...new Set(keys)].sort();
fs.writeFileSync(outputPath, JSON.stringify(result));
} catch (error) {
throw `Localize service: ${error.message}`;
}
}
module.exports = grepKeys;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment