在Node.js中,读取.html文件的目录并在其中搜索元素属性? [英] In Node.js, reading a directory of .html files and searching for element attributes inside them?

查看:314
本文介绍了在Node.js中,读取.html文件的目录并在其中搜索元素属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我甚至无法思考如何做到这一点。基本上,想象一个文件夹,它有一个静态网站。它具有所有的图像,样式和html文件等。使用我的Node应用程序,我想查看该文件夹内的内容,仅获取.html文件,然后选择仅具有data-template =属性的.html文件home''。



我知道这似乎有点奇怪,但它是一个项目,需要用户上传他们的静态网站文件,然后我的Node应用程序对他们的文件做了些什么。



无论如何,只是对某些文件类型的迭代感兴趣,然后在里面寻找它们......任何解决这个问题的帮助都可以帮助我。 / p>

非常感谢,James

解决方案

这段代码会扫描然后查找 .html 文件的内容,然后查找字符串 data-template =home $ b

  var fs = require('fs'); 
$ b $ f .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) ;});});
});

函数inspectFile(contents){
if(contents.indexOf('data-template =home')!= -1){
//做某事$ b如果你需要更多的灵活性,你也可以使用<






  cheerio 模块使用该属性在html文件中查找元素: var cheerio = require('cheerio'); 

函数inspectFile(contents){
var $ = cheerio.load(contents);

if($('html [data-template =home]')。length){
//做某事
}
}


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

解决方案

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

这篇关于在Node.js中,读取.html文件的目录并在其中搜索元素属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆