Node.js Keeps Me Sane June 26, 2013
Scenario: We're rewriting the code for a site but it's pretty much using the same javascript and css currently. So I have a copy of the old version running and a copy of the new version. And something is not perfect in the new site. A Javascript problem. To eliminate differences in javascript as a cause of the problem, here's what I did:
var http = require("http"),
fs = require("fs"),
SyncArray = require("syncarray").SyncArray,
fshelp = require("filesystem");
require("strings");
var web1 = "http://localhost/";
var web2 = "http://oldsite.com/";
var name1 = "new";
var name2 = "old";
function processRequest(baseUrl, url, name, baseDir, finished){
fshelp.ensureFolder(baseDir, function(){
http.get(baseUrl + url, function(resp){
var file = url.lastIndexOf("/") == url.length - 1 ? "_index.html" : url.substring(url.lastIndexOf("/"));
resp.setEncoding("utf8");
var data = "";
resp.on("data", function(d){
data += d;
});
resp.on("end", function(){
fs.writeFile(baseDir + "\\" + file, data, "utf8", function(err){
if (err) console.log("error encountered writing file - " + JSON.stringify(err));
var files = findUrls(data);
console.log(files.length);
var sync = new SyncArray(files);
sync.forEach(function(f, i, arr, finishedOne){
console.log("processing " + f);
processRequest(baseUrl, f, name, baseDir, function(){
finishedOne();
});
}, function(){
finished();
})
});
});
});
});
}
function findUrls(content){
var files = [];
var reg = /(src|href)=["|']([a-zA-Z0-9\._\-\/]*?)["|']/g;
var m = null;
while ((m = reg.exec(content)) != null){
if (m[2].trim().length > 0 && m[2].indexOf(".js") != -1){
files.push(m[2]);
}
}
return files;
}
processRequest(web1, "", name1, "c:\\webs\\" + name1, function(){
console.log("Done " + web1);
});
processRequest(web2, "", name2, "c:\\webs\\" + name2, function(){
console.log("Done " + web2);
});
After that was complete, I then used WinMerge. It would find all javascript files in the html of the home page (what we were having trouble with), and save them all to a folder. It turned out they were identical. But part of narrowing in on the problem is eliminating other possible causes. And I found the problem in the HTML, in where some JS files were being included. Some in head, some below. Putting them all below fixed everything.