Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  117] [ 3]  / answers: 1 / hits: 29342  / 13 Years ago, fri, august 5, 2011, 12:00:00

I can't even begin to think about how this would be done. Basically, imagine a folder and it has a static website in it. It has all the images, styles and html files etc. With my Node application, I want to look inside this folder, get just the .html files only and then pick just the .html files that have the attribute 'data-template=home' inside them.



I know this seems a little odd maybe, but it's for a project that requires the user to upload their static website files and then my Node app does things to them files.



Anyhow, was just curious about iterating over certain filetypes and then looking inside them... Any help with approaching this would really help me.



Many thanks, James


More From » html

 Answers
10

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
}
}

[#90794] Thursday, August 4, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;