In Node.js, reading a directory of .html files and searching for element attributes inside them?
This piece of code will scan for all files in a directory, then read the contents of .html
files and then look for a string data-template="home"
in them.
var fs = require('fs');fs.readdir('/path/to/html/files', function(err, files) { files .filter(function(file) { return file.substr(-5) === '.html'; }) .forEach(function(file) { fs.readFile(file, 'utf-8', function(err, contents) { inspectFile(contents); }); });});function inspectFile(contents) { if (contents.indexOf('data-template="home"') != -1) { // do something }}
If you need more flexibility, you could also use the cheerio
module to look for an element in the html file with that attribute:
var cheerio = require('cheerio');function inspectFile(contents) { var $ = cheerio.load(contents); if ($('html[data-template="home"]').length) { // do something }}
Take a look at the nodejs filesystem module
http://nodejs.org/docs/v0.5.3/api/fs.html
You could use fs.readdir() to get the names of all the files, then read the .html ones to find 'data-template=home'.