2016-09-29 71 views
0

我正在嘗試使用Gulp製作靜態網站。我遇到了一個有趣的翻譯我在前一個版本中編寫的概念以及如何使用Gulp實現它的問題。如何在進行更改之前解析整個gulp流?

其中一個概念,如果我有文件,動態地包含其他文件。

--- 
title: Table of Contents 
include: 
    key: book 
    value: book-1 
--- 

Introduction. 

然後,其他文件包括那個鍵。

--- 
title: Chapter 1 
book: book-1 
--- 
It was a dark and stormy night... 

...和:

--- 
title: Chapter 2 
book: book-1 
--- 

所需的最終結果是:

--- 
title: Table of Contents 
include: 
    key: book 
    value: book-1 
    files: 
    - path: chapters/chapter-01.markdown 
     title: Chapter 1 
     book: book-1 
    - path: chapters/chapter-02.markdown 
     title: Chapter 2 
     book: book-1 
--- 

基本上,通過文件掃描和插入data元素作爲子序列插入該網頁有一個包含。我不知道提前包含的所有類別或標籤(我將30-40個Git存儲庫合併在一起),所以我不想爲每個類別創建一個任務。

我希望什麼是一樣的東西:

return gulp.src("src/**/*.markdown") 
    .pipe(magicHappens()) 
    .pipe(gulp.dest("build")); 

的問題似乎是如何流工作。我無法將兩個方法鏈接在一起,因爲每個文件都從一個管道傳遞到另一個管道。要插入include.files元素,我必須解析所有的輸入文件(它們甚至不在子目錄中),以便在完成之前弄清哪些文件包含在內。

看來我不得不「分流」,解析第一個獲取數據,將第二個鏈接到第一個的末尾,然後使用第二個將結果傳出該方法。我只是不完全確定如何做到這一點,並希望得到一些提示或建議。我的谷歌並沒有真正提出好的建議,甚至沒有提出我重組的提示。謝謝。

回答

0

很多摸索後,我想出了這個:

var through = require('through2'); 
var pumpify = require("pumpify"); 

module.exports = function(params) 
{ 
    // Set up the scanner as an inner pipe that goes through the files and 
    // loads the metadata into memory. 
    var scanPipe = through.obj(
     function(file, encoding, callback) 
     { 
      console.log("SCAN: ", file.path); 
      return callback(null, file); 
     }); 

    // We have a second pipe that does the actual manipulation to the files 
    // before emitting. 
    var updatePipe = through.obj(
     { 
      // We need a highWaterMark larger than the total files being processed 
      // to ensure everything is read into memory first before writing it out. 
      // There is no way to disable the buffer entirely, so we just give it 
      // the highest integer value. 
      highWaterMark: 2147483647 
     }, 
     function(file, encoding, callback) 
     { 
      console.log("UPDATE: ", file.path); 
      return callback(null, file); 
     }); 

    // We have to cork() updatePipe. What this does is prevent updatePipe 
    // from getting any data until it is uncork()ed, which we won't do, or 
    // the scanPipe gets to the end. 
    updatePipe.cork(); 

    // We have to combine all of these pipes into a single one because 
    // gulp needs a single pipe but we have to treat these all as a unit. 
    return pumpify.obj(scanPipe, updatePipe); 
} 

我覺得評論是很清楚,但我有兩個管道合併成(使用pumpify)一個一個,然後用cork停止處理第二個流直到完成第一個流(其自動地將第二個流uncorkd)。由於我有大量的文件,我不得不使用更高的水印來避免第一個捱餓。