Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Node script to find any JS files that are not imported anywhere else.
const fs = require('fs');
const path = require('path');
const childProcess = require('child_process');
const directoryToSearch = process.argv[2];
function getAllFilesInDirectory(dirOrFile) {
if (fs.statSync(dirOrFile).isDirectory()) {
return Array.prototype.concat(...fs.readdirSync(dirOrFile).map((f) => getAllFilesInDirectory(path.join(dirOrFile, f))));
} else if (dirOrFile.indexOf('.js') !== -1) {
return dirOrFile;
}
}
function cleanFileNames(fileNames) {
return fileNames
.filter((fileName) => !!fileName)
.map((fileName) => fileName.replace('.js', ''));
}
function getFilesWithNoReferences(fileNames) {
return fileNames.filter((fileName) => {
try {
childProcess.execSync(`grep -rwl "${fileName}" ${directoryToSearch}`);
return false;
} catch (e) {
return true;
}
});
}
function run() {
const allFileNames = getAllFilesInDirectory(directoryToSearch);
const cleanedFileNames = cleanFileNames(allFileNames);
return getFilesWithNoReferences(cleanedFileNames);
}
console.log(run());
// USAGE:
// execute from directory in which you want to search
// $ node <PATH_TO>/check_deps.js <DIRECTORY_TO_SEARCH>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment