wendy0402
wendy0402

Reputation: 495

log post and get parameters in nodejs

I'm trying to make simple logger for nodejs to handle post and get request also, but I've got problem, because of the non blocking feature of node-js, the parameters is print after the system print the response log here is my code

process.stdout.write(createReqFormat(req));

if(req.method !== 'GET') {
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files){
    process.stdout.write('\n Parameters:' + util.inspect(fields));
  });
}

res.on('finish', function(){
  process.stdout.write(createResFormat(res));
});
next();

for now I only print parameter for post parameter, but this already killing me.

Started POST /post for 127.0.0.1 at Mon Apr 27 2015 09:08:36 GMT+0700 (WIB)
Completed 200 OK
Parameters:{ one: '1', kals: '123', test: '1233', 'test[123]': 'dfjksdjf' }

how to make it print in the right order?

thank you

Upvotes: 2

Views: 796

Answers (1)

Ricardo Stuven
Ricardo Stuven

Reputation: 4814

Parsing the form can actually take more time than finishing the response, so don't call next (or res.send) until you're done with the form.

process.stdout.write(createReqFormat(req));

res.on('finish', function(){
  process.stdout.write(createResFormat(res));
});

if(req.method !== 'GET') {
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files){
    if (err) return next(err);
    process.stdout.write('\n Parameters:' + util.inspect(fields));
    next();
  });
} else {
  next();
}

Upvotes: 1

Related Questions