findstyle
Version:
it will find the inline style tag and internal style in given html file or directory
122 lines (105 loc) • 3.7 kB
JavaScript
var fs = require('fs');
var htmlparser = require("htmlparser2");
var walk = require('walk');
var path = require('path');
var Table = require('cli-table');
if (process.argv.length == 3) {
var fileContent = {};
var htmlDocuments = fs.lstatSync(process.argv[2]).isDirectory() ? readDirectory(process.argv[2], fileContent) : readFile(process.argv[2], fileContent);
var styleDoc = {};
Object.keys(htmlDocuments).forEach(function(key, index) {
parseDoc(key);
});
var table = new Table({
head: ['File Name', 'Internal\nStyle\nCount','Inline\nStyle\nCount'],
colWidths: [54, 10,10]
});
Object.keys(styleDoc).forEach(function(key, index) {
table.push([createMultiline(key), styleDoc[key]['internalCount']||'-', styleDoc[key]['inlineCount']||'-']);
});
console.log(table.toString());
} else {
console.log("pass the filename/directory as arugument");
console.log("Example : findstyle D:\\filename");
return;
}
function createMultiline(name)
{
var temp ='';
for(i=0;i<name.length;i=i+50){
temp = temp+name.substring(i,i+50)+'\n'
}
return temp;
}
function parseDoc(htmlFile)
{
var parser = new htmlparser.Parser({
onopentag: function(name, attribs) {
if (name === "style") {
insertStyleDoc(htmlFile,'internalCount');
}
if (attribs && attribs.style) {
insertStyleDoc(htmlFile,'inlineCount')
}
}
}, {
xmlMode: true
});
parser.write(htmlDocuments[htmlFile]);
parser.end();
}
function insertStyleDoc(filename,type)
{
if(styleDoc.hasOwnProperty(filename))
{
styleDoc[filename][type] = ++styleDoc[filename][type] || 1;
}
else
{
styleDoc[filename] = {};
styleDoc[filename][type] = 1;
}
}
function readDirectory(pathName, fileContent) {
var options, walker;
// To be truly synchronous in the emitter and maintain a compatible api,
// the listeners must be listed before the object is created
options = {
listeners: {
names: function(root, nodeNamesArray) {
nodeNamesArray.sort(function(a, b) {
if (a > b) return 1;
if (a < b) return -1;
return 0;
});
},
directories: function(root, dirStatsArray, next) {
next();
},
file: function(root, fileStats, next) {
var isValidFile = path.extname(root + "\\" + fileStats.name) == '.html' || path.extname(root + "\\" + fileStats.name) == '.jsp';
if (isValidFile) {
var content = fs.readFileSync(root + "\\" + fileStats.name);
fileContent[root + "\\" + fileStats.name] = content;
}
next();
},
errors: function(root, nodeStatsArray, next) {
next();
}
}
};
walker = walk.walkSync(pathName, options);
return fileContent;
}
function readFile(pathName, fileContent) {
var isValidFile = path.extname(pathName) == '.html' || path.extname(pathName) == '.jsp';
if (isValidFile) {
var content = fs.readFileSync(pathName);
fileContent[pathName] = content;
} else {
console.log("invalid file extension");
}
return fileContent;
}