0

So what are the pros and cons of using bodyParser for file uploads?

I mean with bodyParser I get the file into a /var/ directory and then I move it to my directory once its uploaded, it gives me easy access to the name file and other information, but without bodyParser I can do stuff to the files once the 'done' event is triggered..

Is there a way to know when to use bodyParser, and when no to when it comes to files?

maumercado
  • 1,453
  • 4
  • 23
  • 47
  • What sort of stuff can't you do to the files when you use `bodyParser`? – robertklep May 23 '13 at 15:34
  • the events on data dont work, at least with restify... Im just trying to figure out what the pros and cons could be, if any, of using bodyParser with POST or not using bodyParser. Note: Im doing an API so I chose restify not express which is mostly for web, but I know it can be used for an api, just chose restify. – maumercado May 23 '13 at 17:12
  • [This](https://gist.github.com/robertklep/5637962) seems to work just fine. It's just that you can't use *both* `bodyParser` and a custom middleware that also reads the request body, it's one or the other. – robertklep May 23 '13 at 17:48

1 Answers1

0

If you are working with express, you are able to bind a middleware before the bodyParser.

Something like this:

app.use( function( req, res, next ) {
    ... code here runs before bodyparser
    next();
    ... code here runs on the way back (only when there is no error)
});
app.use( express.bodyParser() );
app.use( function( req, res, next ) {
    ... code here runs after bodyparser, before route
    next();
    ... code here runs on the way back (only when there is no error)
});

In this case, you would be able to use both.

Best regards Robert

robsp
  • 216
  • 1
  • 4
  • If the custom middleware reads the message body, this setup isn't going to work because `bodyParser()` expects that there still is a message body to be read when it's called. If there isn't, your app will stall ([demo](https://gist.github.com/robertklep/5637677)). – robertklep May 23 '13 at 17:08
  • No, what you are doing is, putting an event on 'req' inside. That's wrong. For the middleware, just call 'next()' inside the code. – robsp May 26 '13 at 21:05
  • that's not wrong, that's exactly how `bodyParser` works and also how you read the request body in case you don't want `bodyParser` to parse that request body. – robertklep May 27 '13 at 05:35