Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gulp copy HTML and paste to different file

Is is possible using Gulp to copy a portion of HTML (not the entire file) and inject that into a different file?

I have found packages like https://www.npmjs.com/package/gulp-html-replace

and https://www.npmjs.com/package/gulp-inject-string

but they can't actually copy HTML.

like image 804
CyberJunkie Avatar asked Mar 04 '16 22:03

CyberJunkie


1 Answers

Handling HTML with regular expression is never advised, and there are many arguments (1, 2, 3) against that.

The most popular and reliable way to handle an HTML source is by constructing a document model of the source. JSDOM, is one node.js module that provides a good DOM construction API. Here's a demo of how to solve your case with JSDOM:

var fs = require("fs");
var gulp = require("gulp");

var dom = require("jsdom");
var domSerialiser = dom.serializeDocument;

var input = "input.html";
var output = "output.html";

gulp.task("copy-html", function () {
    var extractionPoint = "#extraction-location";
    var insertionPoint = "#insertion-location";

    extractFrom(input, extractionPoint).
            then(insertInto.bind(null, output, insertionPoint)).
            then(saveOutput);
});

function extractFrom(file, section) {
    return new Promise(function (resolve, reject) {
        dom.env({
            file: file,
            done: function (error, window) {
                var portion;

                if (error) {
                    reject(error);
                    return;
                }

                portion = window.document.querySelector(section);

                resolve(portion.outerHTML);
            }
        });
    });
}

function insertInto(file, section, portion) {
    return new Promise(function (resolve, reject) {
        dom.env({
            file: file,
            done: function (error, window) {
                if (error) {
                    reject(error);
                    return;
                }

                section = window.document.querySelector(section);
                // you may prefer to appendChild() instead, your call
                section.outerHTML = portion;

                resolve(domSerialiser(window.document));
            }
        });
    });
}

function saveOutput(data) {
    fs.writeFile(output, data, function (error) {
        if (error) {
            throw error;
        }

        console.log("Copied portion to output successfully.");
    });
}

I hope the example above provides a good basis for you to reach a solution specific to your issue.

like image 75
Igwe Kalu Avatar answered Sep 27 '22 22:09

Igwe Kalu