2016-09-06 46 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

好了,忘了它,错误是因为我在不支持流的管道中使用了另一个插件。 –