KAKAN

Awesome use of the 'async' module in Node.JS

Jun 9th, 2016
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Well, while making an app with express, I saw that the middlewares were taking too long time to load.
  3. This script did cut my load time from 5 seconds to 1 second, hope it helps you too.
  4. */
  5. var async = require('async'), //Load the async module to be used with express.
  6.     express = require('express'), //Load the express module to make the HTTP server.
  7.     app = express(); //Now, we're ready to use our new express app.
  8.  
  9. var morgan = require('morgan'),
  10.     bodyParser = require('body-parser'),
  11.     methodOverride = require('method-override'),
  12.     compression = require('compression');
  13.  
  14. //The awesome function for which I created this snippet:-
  15. function parallel(middlewares)
  16. {
  17.     return function(request,response,next)
  18.     {
  19.         // Documentation on async.each
  20.         // https://www.npmjs.com/package/async#each
  21.         async.each(middlewares,function(middleware,callback){
  22.             //Call/Fire the actual middleware asynchronously.
  23.             middleware(request,response,callback);
  24.         }, next );
  25.     }
  26. }
  27. /*
  28. So, well, now, instead of using this:-
  29. app.use(m1);
  30. app.use(m2);
  31. app.use(m3);
  32. We'll use:-
  33. app.use(parallel[m1,m2,m3]);
  34. Let's have a look below:-
  35. */
  36. //None of the middlewares I'm going to use needs to be in sequence,
  37. //so, we'll use the
  38. //async module to load them asynchronously( which is one of the reasons why we love Node.JS ) instead of synchronous method.
  39. app.use(parallel([
  40.     express.static( __dirname + '/MyPublicFolder' ), /* Just as an example. */
  41.     morgan('dev'),
  42.     compression({'level':6}),
  43.     bodyParser.urlencoded({'extended':'true'}),
  44.     bodyParser.json(),
  45.     bodyParser.json({type: 'application/vnd.api+json'}),
  46.     methodOverride('X-HTTP-Method-Override')
  47. ]));
  48. /* The end. Feel free to use it for other purposes and also, distribute it to others so that they can learn something new too :) */
  49. /* EDIT: Well, I also suggest you to have a look at the other
  50.  functions provided by the async module for both client and server.
  51.  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