admin管理员组文章数量:1426007
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
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
Share Improve this question asked Aug 5, 2011 at 16:23 littlejim84littlejim84 9,26116 gold badges56 silver badges77 bronze badges2 Answers
Reset to default 55This 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'.
本文标签:
版权声明:本文标题:javascript - In Node.js, reading a directory of .html files and searching for element attributes inside them? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737447169a1990195.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论