如何将属性附加到VinylFS对象,以便可以在管道的下游使用它?

时间:2015-07-14 17:06:24

标签: javascript node.js gulp

我正在尝试将属性附加到Node中的VinylFS对象。基本上,我的模块在对象模式下打开变换流,并设置_transform函数以添加属性。 (我通过阅读其他实现的来源,特别是gulp-rename和VinylFS本身来解决这个方法。)

但是,当我在管道中进一步下游时,该属性是未定义的。我怎样才能使下游流消费者能够读取我的属性?我很确定在某个地方存在竞争条件,特别是考虑到控制台输出的顺序,但它在哪里或为什么它发生在我之外。

以下是用于测试的gulpfile.js

'use strict';

var gulp = require('gulp');
var straticParseHeader = require('./index.js');
var log = require('./log.js');

gulp.task('parse', function() {
    gulp.src('new-blog-new-site.md')
        .pipe(straticParseHeader())
        .pipe(log());
});

这是index.js(我真正想做的工作):

'use strict';

var Stream = require('stream');

function parseHeader(obj) {
    var stream = Stream.Transform({objectMode: true});

    stream._transform = function(file, unused, callback) {
        file.test = 'something';
        console.log(file.test);
        callback(null, file);
    };

    return stream;
};

module.exports = parseHeader;

以下是log.js的内容(用于测试下游消费者是否有效的另一个测试文件):

module.exports = function(obj) {
    console.log(obj);
};

最后,这是控制台输出:

% gulp parse
[10:03:04] Using gulpfile ~/Development/stratic-parse-header/gulpfile.js
[10:03:04] Starting 'parse'...
undefined
[10:03:04] 'parse' errored after 6.14 ms
[10:03:04] TypeError: Cannot call method 'on' of undefined
    at Transform.Readable.pipe (_stream_readable.js:495:8)
    at Gulp.<anonymous> (/home/alex/Development/stratic-parse-header/gulpfile.js:10:4)
    at module.exports (/home/alex/Development/stratic-parse-header/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/home/alex/Development/stratic-parse-header/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
    at Gulp.Orchestrator._runStep (/home/alex/Development/stratic-parse-header/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
    at Gulp.Orchestrator.start (/home/alex/Development/stratic-parse-header/node_modules/gulp/node_modules/orchestrator/index.js:134:8)
    at /usr/local/lib/node_modules/gulp/bin/gulp.js:129:20
    at process._tickCallback (node.js:419:13)
    at Function.Module.runMain (module.js:499:11)
    at startup (node.js:119:16)
something

0 个答案:

没有答案