Skip to content

Commit d3e159a

Browse files
committed
Adding grader files
1 parent b0107c6 commit d3e159a

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

checks.json

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
["h1",
2+
".navigation"]

grader.js

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
#!/usr/bin/env node
2+
/*
3+
Automatically grade files for the presence of specified HTML tags/attributes.
4+
Uses commander.js and cheerio. Teaches command line application development
5+
and basic DOM parsing.
6+
7+
References:
8+
9+
+ cheerio
10+
- https://github.com/MatthewMueller/cheerio
11+
- http://encosia.com/cheerio-faster-windows-friendly-alternative-jsdom/
12+
- http://maxogden.com/scraping-with-node.html
13+
14+
+ commander.js
15+
- https://github.com/visionmedia/commander.js
16+
- http://tjholowaychuk.com/post/9103188408/commander-js-nodejs-command-line-interfaces-made-easy
17+
18+
+ JSON
19+
- http://en.wikipedia.org/wiki/JSON
20+
- https://developer.mozilla.org/en-US/docs/JSON
21+
- https://developer.mozilla.org/en-US/docs/JSON#JSON_in_Firefox_2
22+
*/
23+
24+
var fs = require('fs');
25+
var program = require('commander');
26+
var cheerio = require('cheerio');
27+
var HTMLFILE_DEFAULT = "index.html";
28+
var CHECKSFILE_DEFAULT = "checks.json";
29+
30+
var assertFileExists = function(infile) {
31+
var instr = infile.toString();
32+
if(!fs.existsSync(instr)) {
33+
console.log("%s does not exist. Exiting.", instr);
34+
process.exit(1); // http://nodejs.org/api/process.html#process_process_exit_code
35+
}
36+
return instr;
37+
};
38+
39+
var cheerioHtmlFile = function(htmlfile) {
40+
return cheerio.load(fs.readFileSync(htmlfile));
41+
};
42+
43+
var loadChecks = function(checksfile) {
44+
return JSON.parse(fs.readFileSync(checksfile));
45+
};
46+
47+
var checkHtmlFile = function(htmlfile, checksfile) {
48+
$ = cheerioHtmlFile(htmlfile);
49+
var checks = loadChecks(checksfile).sort();
50+
var out = {};
51+
for(var ii in checks) {
52+
var present = $(checks[ii]).length > 0;
53+
out[checks[ii]] = present;
54+
}
55+
return out;
56+
};
57+
58+
var clone = function(fn) {
59+
// Workaround for commander.js issue.
60+
// http://stackoverflow.com/a/6772648
61+
return fn.bind({});
62+
};
63+
64+
if(require.main == module) {
65+
program
66+
.option('-c, --checks <check_file>', 'Path to checks.json', clone(assertFileExists), CHECKSFILE_DEFAULT)
67+
.option('-f, --file <html_file>', 'Path to index.html', clone(assertFileExists), HTMLFILE_DEFAULT)
68+
.parse(process.argv);
69+
var checkJson = checkHtmlFile(program.file, program.checks);
70+
var outJson = JSON.stringify(checkJson, null, 4);
71+
console.log(outJson);
72+
} else {
73+
exports.checkHtmlFile = checkHtmlFile;
74+
}

0 commit comments

Comments
 (0)