Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Strip IIFEs from files in a directory. You'll need minimist and recursive-readdir. Doesn't work on IIFEs that have args passed in
var fs = require('fs');
var path = require('path');
var recursive = require('recursive-readdir');
var argv = require('minimist')(process.argv.slice(2));
var iifepath = path.resolve(process.cwd(), argv.path);
function isIIFEStart (string) {
// whatever you don't know my life
return string === '(function () {' ||
string === '(function(){' ||
string === '(function() {' ||
string === '(function (){';
}
function isIIFEEnd (string) {
return string === '})();' || string === '})()';
}
recursive(iifepath, function (err, files) {
files.forEach((file) => {
if (path.extname(file) !== '.js') {
return;
}
if (file.indexOf('test.js') !== -1) {
return;
}
if (file.indexOf('tests.js') !== -1) {
return;
}
if (file.indexOf('spec.js') !== -1) {
return;
}
if (file.indexOf('legacy/tests') !== -1) {
return;
}
var contents = fs.readFileSync(file, 'utf8');
var lines = contents.split('\n');
// Find the first line with content
let firstLineWithContent;
let i = 0;
while (i < lines.length) {
firstLineWithContent = lines[i];
if (firstLineWithContent !== '') {
break;
}
i++;
}
// If it's not an IIFE, abandon
if (!isIIFEStart(firstLineWithContent)) {
return;
}
let lastLineWithContent;
// Find the last line with content
let k = lines.length - 1;
while (k > 0) {
lastLineWithContent = lines[k];
if (lastLineWithContent !== '') {
break;
}
k--;
}
// If it's not an IIFE, abandon
if (!isIIFEEnd(lastLineWithContent)) {
return;
}
// Remove first line
lines.splice(i, 1);
// Remove last line (-1 for the removed first line)
lines.splice(k - 1, 1);
var strippedFile = lines.join('\n');
fs.writeFileSync(file, strippedFile, 'utf8');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment