Search code examples
node.jsexpressgruntjsvhostsgulp

Can Express run Gulp or Grunt tasks when using vhosts?


I usually start my NodeJS servers with Gulp, with a task similar to:

gulp.task('server', function(){

  var port = gulp.env.port || 80;

  plugins.nodemon({
    script: 'server.js',
    ignore: '*',
  }).on('start', ['source','watch:source']);

});

That compiles all my Jade & Sass templates and dumps them into an assets folder.

For my current project, I'm introducing vhosts, so that I can have a [X].mysite.com for different node apps. I'm not sure how to run my gulpfile when I start the parent server. Should I actually put one gulpfile in the parent directory, and include all tasks for each vhost app in that one? Same question for 'npm install' and 'bower install'.

tl;dr: How do you run a Gulp or Grunt task for each vhost app when using ExpressJS? Same question for 'npm install' and 'bower install'.


Solution

  • use this folder structure:

    vhost(d)
       - website1(d)
         - app.js
         - public(d)
           - index.html
       - website2(d)
         - app.js
         - public
           - index.html
    server.js
    

    your server.js file should look like:

     "use strict";
      var
      express = require('express'),
      vhost = require('vhost'),
      app = express(),
      website1 = require('./vhost/website1/app'),
      website2 = require('./vhost/website2/app'),
      port = process.env.PORT || 8080;
    
    app        
      .use(vhost('localhost', website))
      .use(vhost('cms.localhost', cms))
      .listen(port, function() {
        console.log('server listening on port ' + port);
      });
    

    your app.js file in the website1 folder should look like:

    var
    express = require('express'),
    app = express()
    
    app.use(express.static(__dirname + '/public'));
    app.get('/', function(req, resp) {
      resp.sendFile(__dirname + '/public/index.html');
    });
    
    module.exports = app;
    

    same thing should be for the website2/app.js file

    now write your gulp task and start server.js

    gulp.task('serve', function(){
    
      var port = gulp.env.port || 8080;
    
      plugins.nodemon({
        script: 'server.js',
        ignore: '*',
      }).on('start', ['source','watch:source']);
    
    });
    

    in the main directory of your project run:

    gulp serve
    

    enjoy!