Reputation: 61
Goal: To read a part/particular section of file using NodeJS.
My code:
fs = require('fs')
fs.readFile('/test/index.html', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
console.log(data);
});
Problem: This is reading whole file. And i want to read the text between body tag of html file.
Output in console:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Card</h2>
<div class="card">
<img src="https://www.w3schools.com/howto/img_avatar.png" alt="Avatar" style="width:100%">
<div class="container">
<h4><b>John Doe</b></h4>
<p>Engineer</p>
</div>
</div>
</body>
</html>
Upvotes: 0
Views: 709
Reputation: 6462
You need parse the text, and extract the desired part.
using Regex its possible but problematic. for parse html its recommended use cheerio (see example), in your case (select by node) you can also use "simple" xml reader as xml2js.
using cheerio :
const cheerio = require('cheerio')
fs = require('fs')
fs.readFile('/test/index.html', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
const $ = cheerio.load(data);
console.log($('body'));
});
Upvotes: 1