Node.js event-stream: Where to setMaxListeners?

2019-03-05 00:43发布

问题:

I have searched and searched for this, to no avail. I've combed the web (including Stackoverflow), and the Node docs for an answer, and not found one---that worked (maybe that's just bad searching on my part). I'm working with an event-stream in a gulp config file, and I have a particular task that is hitting the classic "memory leak detected" error from the EventEmitter class. From what I've found, the answer to dealing with this issue seems to be to call the setMaxListeners method of the EventEmitter class; and my research has suggested that the event-stream has a Stream object, which should be an instance of EventEmitter. However, what ever way I try to call setMaxListeners, I get method not found. After exhausting myself researching the issue, I figured I'd bring it to the Node gurus here (I'm assuming this is simple, and I'm just missing something). Here's my code:

return eventStream.merge(
        gulp.src('./jscript/libs/file-one.js'),
        gulp.src('./jscript/libs/filder_one/file-two.js'),
        gulp.src('./jscript/libs/folder_two/file-three.js'),
        gulp.src('./jscript/libs/folder_three/file_four.js'),
        gulp.src('./jscript/libs/folder_four/file_five.js'),
        gulp.src('./jscript/libs/folder_five/file_six.js'), 
        gulp.src('./jscript/libs/file_seven.js'),
        gulp.src('./jscript/libs/file_eight.js'),
        gulp.src('./jscript/lists/rules/*.js')
    )        
    .pipe(concat('my_file.js'))
    .pipe(gulp.dest('./jscript/dist/'))
    .pipe(rename('my_file.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest('./jscript/dist/'));

Thanks!

回答1:

This is not a direct answer to your question, but you can pass an array of glob patterns to 'gulp.src()' instead of merging multiple 'gulp.src()'s. Doesn't it solve your problem?

https://github.com/gulpjs/gulp/blob/master/docs/API.md#gulpsrcglobs-options

EDIT

As a direct answer, the following worked for me:

var merged = eventStream.merge(...);
merged.setMaxListeners(0);
return merged.pipe(...);

While event listeners are added in the merge function, the listener count seems to be checked between ticks of the event loop. So we can setMaxListeners right after adding listeners.



回答2:

In Node.js 0.12 (soon to be released) you'll be able to set the max for all emitters:

var events = require('events');
events.EventEmitter.defaultMaxListeners = 100;

More in the relevant commit.