Skip to content

Instantly share code, notes, and snippets.

@wayspurrchen
Created September 15, 2016 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wayspurrchen/b8879003a0cd3b6c703aa8e09cb6ad4f to your computer and use it in GitHub Desktop.
Save wayspurrchen/b8879003a0cd3b6c703aa8e09cb6ad4f to your computer and use it in GitHub Desktop.
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