Gulp/Node: isStream=true 的文件内容流过滤器

Gulp/Node: file content stream filter with isStream=true

我还没有在网上找到任何关于如何手动处理 isStream 模式的示例。我能找到的只有 prefixing/appending text and letting through() handle the actual streaming:

if (file.isStream()) {
    var stream = through();
    stream.write(prefixText);
    file.contents = file.contents.pipe(streamer);
}

不过我想通过encodeURI()过滤文件内容。我该怎么做?

你可能想要这样的东西:

if (file.isStream()) {
  var
    encoding = 'utf8',
    contents = [];

  function write (chunk, enc, done) {
    contents.push(chunk);
    done();
  }

  function end (done) {
    // Concat stored buffers and convert to string.
    contents = Buffer.concat(contents).toString(encoding);
    // encodeURI() string.
    contents = encodeURI(contents);
    // Make new buffer with output of encodeURI().
    contents = Buffer(contents, encoding);
    // Push new buffer.                
    this.push(contents);
    done();
  }

  // This assumes you want file.contents to be a stream in the end.
  file.contents = file.contents.pipe(through(write, end));
}