最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Gulp copy HTML and paste to different file - Stack Overflow

programmeradmin1浏览0评论

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

and

but they can't actually copy HTML.

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./package/gulp-html-replace

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

but they can't actually copy HTML.

Share Improve this question asked Mar 4, 2016 at 22:33 CyberJunkieCyberJunkie 22.7k61 gold badges154 silver badges219 bronze badges 5
  • 2 How do you identify the portion to be copied ? Is there a container element for the content? – 11thdimension Commented Mar 4, 2016 at 22:45
  • i would use a RegExp, surrounding the HTML with special ments if needed. – dandavis Commented Mar 4, 2016 at 23:12
  • @11thdimension yes there could be a container or ments – CyberJunkie Commented Mar 5, 2016 at 18:36
  • 2 This seems like an XY problem. – Evan Davis Commented Mar 7, 2016 at 14:32
  • what do you mean by credible or official source? What could be credible and what could possibly be official? – Igwe Kalu Commented Mar 9, 2016 at 22:54
Add a ment  | 

3 Answers 3

Reset to default 3 +250

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.

you can do it using fs and replace, I don't know if it's the best way, but it's works for me.

  gulp.task('injectHtml', function() {
    return gulp.src('/dir/file_to_inject.html')
      .pipe(replace('<!-- injecthere -->', function() {
        var htmlContent = fs.readFileSync('/home/file_source.html', 'utf8');
        //regex to get the div content
        return htmlContent.match(/<div id="myDiv">(.*?)<\/div>/)[0];
      }))
      .pipe(gulp.dest('/dir'));
  });

file_source.html

<html>
 <div id="myDiv">test div</div>
</html>

file_to_inject.html

<html>
 <!-- injecthere -->
</html>

Yes, I typically use through2 whenever I want to inject some custom code into the pipe:

var gulp = require('gulp');
var through2 = require('through2');
var fs = require('fs');

gulp.task('default', function(){
  gulp.src('./recipient.html')
    .pipe(through2.obj(function(file, enc, done){
      fs.readFile('./donor.html', function(err, data){
        if(err) throw "Something went horribly wrong.";
        // extract from data the HTML you want to insert
        var contents = file.contents.toString('utf8');
        // insert HTML into `contents`
        file.contents = new Buffer(contents);
        this.push(file)
        done();
      });
    });
});

This will pipe the recipient html file through gulp, then, read in the donor html file contents. From there you can manipulate both to your heart's content. Then you simply take the result, put it back into the file object, and push that sucker back into the gulp pipeline.

发布评论

评论列表(0)

  1. 暂无评论