Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Well, while making an app with express, I saw that the middlewares were taking too long time to load.
- This script did cut my load time from 5 seconds to 1 second, hope it helps you too.
- */
- var async = require('async'), //Load the async module to be used with express.
- express = require('express'), //Load the express module to make the HTTP server.
- app = express(); //Now, we're ready to use our new express app.
- var morgan = require('morgan'),
- bodyParser = require('body-parser'),
- methodOverride = require('method-override'),
- compression = require('compression');
- //The awesome function for which I created this snippet:-
- function parallel(middlewares)
- {
- return function(request,response,next)
- {
- // Documentation on async.each
- // https://www.npmjs.com/package/async#each
- async.each(middlewares,function(middleware,callback){
- //Call/Fire the actual middleware asynchronously.
- middleware(request,response,callback);
- }, next );
- }
- }
- /*
- So, well, now, instead of using this:-
- app.use(m1);
- app.use(m2);
- app.use(m3);
- We'll use:-
- app.use(parallel[m1,m2,m3]);
- Let's have a look below:-
- */
- //None of the middlewares I'm going to use needs to be in sequence,
- //so, we'll use the
- //async module to load them asynchronously( which is one of the reasons why we love Node.JS ) instead of synchronous method.
- app.use(parallel([
- express.static( __dirname + '/MyPublicFolder' ), /* Just as an example. */
- morgan('dev'),
- compression({'level':6}),
- bodyParser.urlencoded({'extended':'true'}),
- bodyParser.json(),
- bodyParser.json({type: 'application/vnd.api+json'}),
- methodOverride('X-HTTP-Method-Override')
- ]));
- /* The end. Feel free to use it for other purposes and also, distribute it to others so that they can learn something new too :) */
- /* EDIT: Well, I also suggest you to have a look at the other
- functions provided by the async module for both client and server.
- And I also suggest you to have a look at basket.js to cache and make your website even more faster. */
Add Comment
Please, Sign In to add comment