WebFund 2016W: Tutorial 1: Difference between revisions
Line 6: | Line 6: | ||
===simplegrep_sync.js=== | ===simplegrep_sync.js=== | ||
< | <source line lang="javascript"> | ||
var fs = require('fs'); | var fs = require('fs'); | ||
Line 26: | Line 26: | ||
} | } | ||
} | } | ||
</ | </source> | ||
===simplegrep_async.js=== | ===simplegrep_async.js=== | ||
< | <source line lang="javascript"> | ||
var fs = require('fs'); | var fs = require('fs'); | ||
Line 54: | Line 54: | ||
fs.readFile(filename, 'utf-8', returnMatches); | fs.readFile(filename, 'utf-8', returnMatches); | ||
</ | </source> |
Revision as of 02:39, 11 January 2016
This tutorial is not yet finalized.
Code
simplegrep_sync.js
var fs = require('fs');
if (process.argv.length < 4) {
console.error('Not enough parameters given. Try this: ' +
'"node findinfile_sync term filename.txt"');
process.exit(1);
}
var searchterm = process.argv[2];
var filename = process.argv[3];
var rawContents = fs.readFileSync(filename, 'utf-8');
var lines = rawContents.split('\n');
for (i = 0; i < lines.length; i++) {
if (lines[i].indexOf(searchterm) > -1) {
console.log(lines[i]);
}
}
simplegrep_async.js
var fs = require('fs');
if (process.argv.length < 4) {
console.error('Not enough parameters given. Try this: ' +
'"node findinfile_sync term filename.txt"');
process.exit(1);
}
var searchterm = process.argv[2];
var filename = process.argv[3];
var returnMatches = function(err, rawContents) {
var lines = rawContents.split('\n');
lines.forEach(function(theLine) {
if (theLine.indexOf(searchterm) > -1) {
console.log(theLine);
}
});
}
fs.readFile(filename, 'utf-8', returnMatches);