forked from heroku/node-js-sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grader.js
57 lines (49 loc) · 1.65 KB
/
grader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env node
/*
Automatically grade files for the presence of specified HTML tags/attributes. Uses commander.js and cheerio. Teaches command line application development and basic DOM parsing.
*/
var fs = require('fs');
var program = require('commander');
var cheerio = require('cheerio');
var HTMLFILE_DEFAULT = "index.html";
var CHECKSFILE_DEFAULT = "checks.json";
var assertFileExists = function(infile) {
var instr = infile.toString();
if (!fs.existsSync(instr)) {
console.log("%s does not exist. Exiting.", instr);
process.exit(1);
}
return instr;
};
var cheerioHtmlFile = function(htmlFile) {
return cheerio.load(fs.readFileSync(htmlfile));
};
var loadChecks = function(checksfile) {
return JSON.parse(fs.readFileSync(checksfile));
};
var checkHtmlFile = function(htmlfile, checksfile) {
$ = cheerioHtmlFile(htmlfile);
var checks = loadChecks(checksfile).sort();
var out = {};
for (var ii in checks) {
var present = $(checks[ii]).length > 0;
out[checks[ii]] = present;
}
return out;
};
var clone = function(fn) {
// Workaround for commander.js issue.
// http://stackoverflow.com/a/6772648
return fn.bind({});
};
if (require.main == module) {
program
.option('-c, --checks <check_file>', 'Path to checks.json', clone(assertFileExists), CHECKSFILE_DEFAULT)
.option('-f, --file <html_file>', 'Path to index.html', clone(assertFileExists), HTMLFILE_DEFAULT)
.parse(process.argv);
var checkJson = checkHtmlFile(program.file, program.checks);
var outJson = JSON.sringify(checkJson, null, 4);
console.log(outJson);
} else {
exports.checkHtmlFile = checkHtmlFile;
}