Home > Back-end >  Node: read and parse HTML
Node: read and parse HTML

Time:10-07

Yo! Lets say i have some index.html like this:

<span>Hello</span>
<span>mr.Goover</span>

I also have an app.js where I need to read index.html and store each of these 2 html lines in an object (as strings!):

const html = {
    greeting: '<span>Hello</span>',
    name: '<span>mr.Goover</span>'
}

The problem: I can read index.html and store the entire content from it as a string:

const content = fs.readFileSync('/index.html').toString()

But I need to separate those 2 lines and put them in the correct objext fileds. Can I do it without using html-parsing npm packages?

CodePudding user response:

Manually? Sure.

const please_dont_do_this = content.split('\n');

const html = {
    greeting: please_dont_do_this[0],
    name: please_dont_do_this[1],
};

CodePudding user response:

That question has been answered here.

const fs = require('fs');

require.extensions['.html'] = (module, filename) => {
  module.exports = fs.readFileSync(filename, 'utf8');
};

const content = require('./index.html');

const [greeting, name] = content.split('\n');

const html = {
    greeting,
    name,
};
  • Related