Cannot listen / handle EventEmitter in callback

Using Mongoose to work with MongoDB, however, when trying to process events (for example, parsing multi-page downloads using Formidable ) emitted in the request callback, no luck. Any idea why, or a fix?

Models

var mongoose = require('mongoose'); function User() { return mongoose.model('users', new mongoose.Schema({ username: String, email: String, name: String })); } exports = module.exports = User; 

Server

 /** Example HTTP server */ var http = require('http'), mongoose = require('mongoose'), formidable = require('formidable'), models = require('./models'); mongoose.connect('mongodb://localhost/test'); var User = new models.User(); var form = new formidable.IncomingForm(); http.createServer(function(request, response) { User.findOne({ username: 'wayoutmind' }, function(error, user) { // Does not print to console, Event listener blackhole? form.on('field', function(name, value) { console.log(name + ':' + value); }); form.parse(request); }); }).listen(1337); 
+4
source share
1 answer

Can you confirm that the parsing of the form works independently, i.e. if you omit the call to the database (findOne)?

If so, can you try customizing your form.on() callbacks and running form.parse() before calling User.findOne() ? A form object can internally listen for "data" events upon request that have already occurred by the time the callback from findOne() .

You can also try using request.pause () and request.resume () (hackier):

 http.createServer(function(request, response) { request.pause(); User.findOne({ username: 'wayoutmind' }, function(error, user) { form.on('field', function(name, value) { console.log(name + ':' + value); }); request.resume(); form.parse(request); }); }).listen(1337); 
+1
source

Source: https://habr.com/ru/post/1394132/


All Articles