Javascript 在 Node.js 中,读取 .html 文件的目录并在其中搜索元素属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6959462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Node.js, reading a directory of .html files and searching for element attributes inside them?
提问by littlejim84
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.
我什至无法开始考虑如何做到这一点。基本上,想象一个文件夹,其中有一个静态网站。它包含所有图像、样式和 html 文件等。对于我的 Node 应用程序,我想查看此文件夹内部,仅获取 .html 文件,然后仅选择具有属性“data-template=”的 .html 文件家”'在他们里面。
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.
我知道这可能看起来有点奇怪,但它适用于需要用户上传他们的静态网站文件然后我的 Node 应用程序对他们的文件执行操作的项目。
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
非常感谢,詹姆斯
回答by mak
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.
这段代码将扫描目录中的所有文件,然后读取.html
文件的内容,然后data-template="home"
在其中查找字符串。
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:
如果您需要更大的灵活性,您还可以使用该cheerio
模块在 html 文件中查找具有该属性的元素:
var cheerio = require('cheerio');
function inspectFile(contents) {
var $ = cheerio.load(contents);
if ($('html[data-template="home"]').length) {
// do something
}
}
回答by shelman
Take a look at the nodejs filesystem module
看一下 nodejs 文件系统模块
http://nodejs.org/docs/v0.5.3/api/fs.html
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'.
您可以使用 fs.readdir() 获取所有文件的名称,然后读取 .html 文件以找到“data-template=home”。