2016-09-06 79 views
2

嗯,我正在嘗試爲gulp任務中的每個文件執行一個inkscape任務。使用Inkscape在gulp任務中使用SVG時遇到問題

這個想法是轉換我在複合路徑中的每個SVG文件(一個SVG只由一個複雜路徑組成)。

我試圖像這樣的東西來實現這一目標:

gulp.task('minify-shapes', function() { 
    function makeChange() { 
     var Stream = require('stream'); 

     function transform(file, cb) { 
      var svgConverter = new Inkscape(['--verb=ObjectToPath', '--export-plain-svg']); 

      var stdout = new Stream(); 
      var bufs = []; 

      console.log(file.history); 

      stdout.on('data', function(d) { 
       bufs.push(d); 
      }); 

      stdout.on('end', function() { 
       var buf = Buffer.concat(bufs); 

       file.contents = buf; 

       cb(null, file); 
      }); 

      file.pipe(svgConverter).pipe(stdout); 
     } 

     return require('event-stream').map(transform); 
    } 

    return gulp.src('app/assets/shapes/**/*.svg') 
     .pipe(makeChange()) 
     .pipe(gulp.dest('app/assets/shapes')); 
}); 

的問題是,這個NPM包Inkscape的工作與流,所以我應該以某種方式管Inkscape的輸出和寫回吞掉file.contents 。

這似乎不起作用,因爲此Inkscape流輸出到緩衝區的轉換是異步的,所以它不能與gulp任務流同步。

我收到的錯誤是:

stream.js:59 
    dest.end(); 
     ^

TypeError: dest.end is not a function 
    at Inkscape.onend (stream.js:59:10) 
    at emitNone (events.js:91:20) 
    at Inkscape.emit (events.js:185:7) 
    at Inkscape.<anonymous> (node_modules\inkscape\lib\Inkscape.js:161:26) 
    at emitNone (events.js:91:20) 
    at ReadStream.emit (events.js:185:7) 
    at endReadableNT (_stream_readable.js:926:12) 
    at _combinedTickCallback (internal/process/next_tick.js:74:11) 
    at process._tickCallback (internal/process/next_tick.js:98:9) 

有人可以幫助我嗎?

回答

2

file.contents屬性不一定是Buffer。它也可以流式傳輸。所有你需要做的就是通過buffer:false optiongulp.src()

然後,它與被調用.pipe()創建的新流替換現有file.contents流一樣簡單:

var gulp = require('gulp'); 
var map = require('event-stream').map; 
var Inkscape = require('inkscape'); 

gulp.task('minify-shapes', function() { 
    return gulp.src('app/assets/shapes/**/*.svg', { buffer:false }) 
    .pipe(map(function(file, done) { 
     var svgConverter = new Inkscape([ 
     '--verb=ObjectToPath', 
     '--export-plain-svg' 
     ]); 

     file.contents = file.contents.pipe(svgConverter); 
     done(null, file); 
    })) 
    .pipe(gulp.dest('app/assets/shapes')); 
}); 
+0

您好,感謝您的回答,這個代碼看起來比我好多了:)不過,現在我收到另一個錯誤: [20:16:28]開始'minify-shapes'... events.js:160 throw er; //未處理'錯誤'事件 ^ 錯誤:不支持流式處理 –

+0

好了,忘了它,錯誤是因爲我在不支持流的管道中使用了另一個插件。 –