D
D
denis26012018-09-27 22:56:28
Node.js
denis2601, 2018-09-27 22:56:28

How to find the data-* value in an HTML file using node.js?

I am writing a plugin for gulp, the task is as follows, in the stream when assembling html files, find data-skin="site-red" in the same file, take the data value and replace the links to styles in the same files.
It was like this:

<html lang="en" data-skin="site-red">
<head>

  <title>Title</title>
  <meta charset="utf-8">

  <link id="skins" rel="stylesheet" href="css/assets/style.css">
</head>
...

and after assembly it should look like this:
<html lang="en" data-skin="site-red">
<head>

  <title>Title</title>
  <meta charset="utf-8">

  <link id="skins" rel="stylesheet" href="css/site-red/assets/style.css">
</head>
...

I figured out how to read the file, here is the initial code of the future plugin:
'use strict';

var Transform = require('readable-stream/transform');

module.exports = function repl() {
  return new Transform({
    objectMode: true,
    transform: function replTransform(file, enc, cb) {
      if (file.isNull()) {
        cb(null, file);
        return;
      }

      if (file.isStream()) {
        console.log('Stream');
        console.log(file.contents);
        return cb(null, file);
      }

      if (file.isBuffer()) {
        const data = file.contents.toString();

        console.log('Buffer');
        console.log(data);

        file.contents = new Buffer(data);
        return cb(null, file);
      }

    }
  })
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
monochromer, 2018-10-04
@denis2601

If you want to parse html files yourself, then you are welcome, but it’s better to use sheerio

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question