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

时间:2015-04-25 07:07:06

标签: node.js stream gulp

我还没有在网上找到关于如何手动处理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()过滤文件内容。我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可能需要以下内容:

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));
}