在gulp任务中使用Inkscape处理SVG时遇到问题

Having problems to work with SVG using Inkscape in gulp task

本文关键字:SVG 处理 遇到 问题 Inkscape gulp 任务      更新时间:2023-09-26

嗯,我正在尝试对gulp任务中的每个文件执行inkscape任务。

这个想法是转换我在复合路径(仅由一个复杂路径组成的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输出并写回gulp 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)

有人能帮我吗?

file.contents属性不一定是Buffer。也可以是流媒体。您所要做的就是将buffer:false选项传递给gulp.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'));
});