h. Oo
h. Oo

Reputation: 371

node js how parser libs work

I just cant understand how parser libraries like multer or even body-parser work. from what data in the post request they create the request.body. if i upload a file using html form

<form method="post" action="/upload"  enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="submit" value="upload">
</form> 

and I just post the request as is, I couldn't find any part of the the file that was uploaded (like file name or size...). But when i use multer it just appear in the request.body and request.file, how?

Upvotes: 0

Views: 22

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123493

The body of the request, containing the data from the form (or ajax request, etc.), has to be read explicitly. It's accessible by using the request, an IncomingMessage, as a Readable stream.

For example, a basic take on bodyParser.urlencoded() could be the following, retrieving the body from the request in "flowing mode" by using the 'data' and 'end' events:

var querystring = require('querystring');

app.use(function (request, response, next) {
    // skip middleware if not relevant to the current request
    if ('application/x-www-form-urlencoded' !== request.headers['content-type'])
        return next();

    var chunks = [];

    // The 'data' event can occur multiple times
    // each given only part of the message.
    // So, just collect the parts at this point.
    request.on('data', function (chunk) {
        chunks.push(chunk);
    });

    // The 'end' event occurs once after all 'data' chunks have arrived.
    // Now, it's ready to parse.
    request.on('end', function () {
        try {
            // combine all of the 'data' chunks together
            var bodyContent = Buffer.concat(chunks);

            // parse and modify the `request` so the data is accessible later
            request.body = querystring.parse(bodyContent);

            next(); // success
        } catch (error) {
            next(error);
        }
    });

    request.on('error', function (error) {
        next(error);
    });
});

Upvotes: 1

Related Questions