Skip to content

Instantly share code, notes, and snippets.

@silvae86
Created June 11, 2017 20:54
Show Gist options
  • Save silvae86/1e1e277a95d7cf67a9693130fd730918 to your computer and use it in GitHub Desktop.
Save silvae86/1e1e277a95d7cf67a9693130fd730918 to your computer and use it in GitHub Desktop.
Replace typeof var !== "undefined" in file using JavaScript
fs = require('fs')
var file = process.argv[2];
function replaceAll(str, needle, replacement) {
return str.split(needle).join(replacement);
}
console.log("Processing file " + file);
fs.readFile(file, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var equalsUntitledMatches = data.match(/typeof [0-9a-zA-Z\[\]\.]* [!=]== \"undefined\"/g);
//console.log(JSON.stringify(equalsUntitledMatches, null, 4));
for (var i = 0; i < equalsUntitledMatches.length; i++) {
var before = equalsUntitledMatches[i];
var variableRegex = new RegExp(/typeof ([0-9a-zA-Z\[\]\.]*) ([!=]==) \"undefined\"/g);
var variableMatches = variableRegex.exec(before);
var operator = variableMatches[2];
if(operator === "!==")
{
var after = "!isNull("+variableMatches[1]+")";
}
else if(operator === "===")
{
var after = "isNull("+variableMatches[1]+")";
}
else
{
throw new Error("Unrecognised operator "+ operator +" found at file: ")
}
console.log(before +" ======> "+ after);
data = replaceAll(data, before, after);
}
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment