2

So, I served an html page with a node.js file, and I want to know how I can get an element in the html file in that node.js file.

I have tried youtube and google and can't find what I am looking for.

Here is my code:

HTML

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <p id='iwwinm'>I want to be stored in a node.js var? How?!</p>
  </body>
</html>

Node.js

const http = require('http')
const fs = require('fs')

__dirname = path.resolve();

let server = http.createServer(function(req,res) {
  console.log('req made: ' + req.url)
  res.writeHead(200, {'Content-Type': 'text/html'});
  var mRS = fs.createReadStream(__dirname + '/index.html', 'utf8');
  mRS.pipe(res)
})

function log() {
  console.log('hi')
}

server.listen(3000)

In the end, I simply want to get the content of that p element, and log it in the node.js console!

Fahim Al Mahmud Ashik
  • 1,083
  • 10
  • 26
bu1d3r
  • 21
  • 1
  • 2
  • 4
  • Aren't you going about this backwards? You're serving up your file from your node server and THEN you're trying to get a value from the page you just served? Is that correct? – Chris Sep 07 '19 at 03:46

1 Answers1

3

you can use cheerio to parse html, then query element like jquery.

const cheerio = require('cheerio')
const $ = cheerio.load(`
<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <p id='iwwinm'>I want to be stored in a node.js var? How?!</p>
  </body>
</html>
`)

console.log($('#iwwinm').text(''))
JKong
  • 254
  • 1
  • 8
  • See also this related question on how to extract an html element from a string: https://stackoverflow.com/questions/32894426/extract-element-by-id-from-string – exchange Aug 16 '20 at 09:34
  • and this answer on how to implement it for node.js: https://stackoverflow.com/questions/11398419/trying-to-use-the-domparser-with-node-js contains some alternatives to cheerio like jsdom: https://www.npmjs.com/package/jsdom – exchange Aug 16 '20 at 09:40