-1

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?

  • If this is the entire extent of the project - you will only ever have two sets of simply formatted `` tags, then you can just use any number of simplified ways to parse this. You could use a regex or you could use `.indexOf()` to find the different pieces. If the content can actually be real HTML with all the assorted attributes and other tags, then for goodness sake, use a real HTML parser. – jfriend00 Oct 06 '21 at 18:11
  • And, since the HTML contains no info at all about what is a `greeting` and what is a `name` or what might be some other property, you'd have to provide that info too. – jfriend00 Oct 06 '21 at 18:13

2 Answers2

0

Manually? Sure.

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

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

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,
};
Giusseppe
  • 147
  • 7