GithubHelp home page GithubHelp logo

ericclemmons / grunt-express-server Goto Github PK

View Code? Open in Web Editor NEW
248.0 9.0 64.0 106 KB

Grunt task for running an Express Server that works great with LiveReload + Watch/Regarde

License: MIT License

JavaScript 96.78% CoffeeScript 3.22%

grunt-express-server's Introduction

grunt-express-server

Build Status Dependencies devDependencies

Simple grunt task for running an Express server that works great with LiveReload + Watch/Regarde

Getting Started

This plugin requires Grunt >=0.4.0

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-express-server --save-dev

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-express-server');

The express task

Setup

In your project's Gruntfile, you can create one or multiple servers:

grunt.initConfig({
  express: {
    options: {
      // Override defaults here
    },
    dev: {
      options: {
        script: 'path/to/dev/server.js'
      }
    },
    prod: {
      options: {
        script: 'path/to/prod/server.js',
        node_env: 'production'
      }
    },
    test: {
      options: {
        script: 'path/to/test/server.js'
      }
    }
  }
});

You can override the default options either in the root of the express config or within each individual server task.

Default options

  express: {
    options: {
      // Override the command used to start the server.
      // (do not use 'coffee' here, the server will not be able to restart
      //  see below at opts for coffee-script support)
      cmd: process.argv[0],

      // Will turn into: `node OPT1 OPT2 ... OPTN path/to/server.js ARG1 ARG2 ... ARGN`
      // (e.g. opts: ['node_modules/coffee-script/bin/coffee'] will correctly parse coffee-script)
      opts: [ ],
      args: [ ],

      // Setting to `false` will effectively just run `node path/to/server.js`
      background: true,

      // Called when the spawned server throws errors
      fallback: function() {},

      // Override node env's PORT
      port: 3000,

      // Override node env's NODE_ENV
      node_env: undefined,

      // Enable Node's --harmony flag
      harmony: false,

      // Consider the server to be "running" after an explicit delay (in milliseconds)
      // (e.g. when server has no initial output)
      delay: 0,

      // Regular expression that matches server output to indicate it is "running"
      output: ".+",

      // Set --debug (true | false | integer from 1024 to 65535, has precedence over breakOnFirstLine)
      debug: false,

      // Set --debug-brk (true | false | integer from 1024 to 65535)
      breakOnFirstLine: false,

      // Object with properties `out` and `err` both will take a path to a log file and
      // append the output of the server. Make sure the folders exist.
      logs: undefined

    }
  }

Usage

By default, unless delay or output has been customized, the server is considered "running" once any output is logged to the console, upon which control is passed back to grunt.

Typically, this is:

Express server listening on port 3000

If your server doesn't log anything, the express task will never finish and none of the following tasks, after it, will be executed. For example - if you have a development task like this one:

grunt.registerTask('rebuild', ['clean', 'browserify:scripts', 'stylus', 'copy:images']);
grunt.registerTask('dev', ['rebuild', 'express', 'watch']);

If you run the dev task and your server doesn't log anything, 'watch' will never be started.

This can easily be avoided, if you log something, when server is created like that:

var server = http.createServer( app ).listen( PORT, function() {
    console.log('Express server listening on port ' + PORT);
} );

If you log output before the server is running, either set delay or output to indicate when the server has officially started.

Starting the server

If you have a server defined named dev, you can start the server by running express:dev. The server only runs as long as grunt is running. Once grunt's tasks have completed, the web server stops.

Stopping the server

Similarly, if you start the dev server with express:dev, you can stop the server with express:dev:stop.

grunt.initConfig({
  watch: {
    express: {
      files:  [ '**/*.js' ],
      tasks:  [ 'express:dev' ],
      options: {
        spawn: false // for grunt-contrib-watch v0.5.0+, "nospawn: true" for lower versions. Without this option specified express won't be reloaded
      }
    }
  }
});

grunt.registerTask('server', [ 'express:dev', 'watch' ])

Important: Note that the spawn: false options only need be applied to the watch target regarding the express task. You may have other watch targets that use spawn: true, which is useful, for example, to reload CSS and not LESS changes.

watch: {
  options: {
    livereload: true
  },
  express: {
    files:  [ '**/*.js' ],
    tasks:  [ 'express:dev' ],
    options: {
      spawn: false
    }
  },
  less: {
    files: ["public/**/*.less"],
    tasks: ["less"],
    options: {
      livereload: false
    }
  },
  public: {
    files: ["public/**/*.css", "public/**/*.js"]
  }
}

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using Grunt.

Release History

  • v0.5.3 - Update peerDeps and enable travis build against Node 4
  • v0.5.2 - Add hardStop flag (#99)
  • v0.5.1 - Add harmony flag (#86)
  • v0.5.0 - Add breakOnFirstLine option, support for debug ports and fix bugs. Details: (#68, #70, #73)
  • v0.4.19 – Use process.env.PORT before 3000 (#59)
  • v0.4.18 – Fix for when running the node debugger (#57)
  • v0.4.17 – Update devDependencies...again
  • v0.4.16 – Update devDependencies
  • v0.4.15 – Recommend using local coffee with additional arguments (#50)
  • v0.4.14 – Attempt to fix issues running Coffeescript (#54)
  • v0.4.13 – Add --nodejs for Coffeescript users (#37)
  • v0.4.12 – Only remove this task's listeners (#39)
  • v0.4.11 – Revert v0.4.10 until Travis can reproduce it
  • v0.4.10 – Another attempt to fix #28 & #30's server restarting issue (#31)
  • v0.4.9 – Revert v0.4.8 until #30 is resolved
  • v0.4.8 – Fix issue with start/restarting multiple instances (#29)
  • v0.4.7 – Remove broken error option (#27)
  • v0.4.6 – Store running servers on process._servers[target] (#22)
  • v0.4.5 – Support multiple servers running at once (#23)
  • v0.4.4 - Fix for using grunt-env to change environments, thanks to @FredrikAppelros (#20)
  • v0.4.3 - Add cmd option that defaults to Node, but can be set to coffee for Coffeescript support, thanks to @JonET (#15)
  • v0.4.2 - Add debug option that gets enables Node's debugger, ideally for use with node-inspector
  • v0.4.1 - Add node_env option that sets NODE_ENV when running the server & restores original env upon closing, thanks to @jgable!
  • v0.4.0
    • Add delay option that, when set, passes control back to grunt after timeout
    • Add output regular expression option that, when set, waits for matching message before passing control back to grunt
  • v0.3.1 - Try to force notification that express task has finished as much as possible
  • v0.3.0 - express is now a multitask with customizable options, better error handling and :stop task
  • v0.2.0
    • Change express-server task to express
    • Config is set via express: '...' instead of server: { script: '...' }
  • v0.1.0 - Initial import from Genesis Skeleton & release

Bitdeli Badge

grunt-express-server's People

Contributors

bitdeli-chef avatar daftmonk avatar ericclemmons avatar guifromrio avatar jaswilli avatar jdewit avatar jgable avatar jitheshgopan avatar jlsutherland avatar jnwelzel avatar jonet avatar justcfx2u avatar mpderbec avatar nicroto avatar outring avatar paulgrock avatar paulpflug avatar rfink avatar sebgie avatar sorahn avatar thgil avatar yosuke-furukawa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunt-express-server's Issues

Need a way to do node --debug-brk

The 'debug' option is great, and we would like to also be able to do a '--debug-brk' with Node so that we can debug our server script from the first line.

(We have code changes ready for this, we'll do a Pull Request shortly.)

Error: listen EADDRINUSE

I'm getting an Error: listen EADDRINUSE error when using this module with watch.

This is my Gruntfile:

        watch: {
            all: {
                files: ['app/**/*.js', 'spec/**/*.js'],
                tasks: ['jshint', 'express']
            }
        },

        express: {
            dev: {
                options: {
                    script: 'app.js',
                    port: 9001
                }
            }
        }

Remove livereload example

This module has been deprecated in favor of the watch task which has it built it.

This module is great, much simpler than grunt-express which I had a look at before this. Nice job!

How to configure modRewrite or middleware/connect?

I am trying to configure URL rewriting with grunt-express-server in a yeoman generated angular-fullstack site. Unfortunately I tried any conceivable way of configuring connect, livereload and the likes but for some reason I am unable to add HTML rewrite capabilities to the grunt serve task. The end result is that my angularjs app running in html5mode results in a 404 every time the page is live reloaded. Do you happen to have a working example that would show how to configure connect or middleware in a lifereload task?

Yo generator that includes grunt-express-server is located here

coffeescript needs --nodejs with --debug

We made an adjustment to our tasks/lib/server.js file to include the following.

      if(options.debug) {
        options.args.unshift('--debug');
        if(options.cmd === 'coffee') {
          options.args.unshift('--nodejs');
        }
      }

I can send along a proper pull request later. if you want it.

express-server + watch isn't restarting when SyntaxErrors occur

So I'm not sure if this is the same issue as described in #27, but basically everything is working great with the exception that if I introduce a syntax error into my server code watch isn't restarting (and I have to manually restart grunt from cmd). Here is the relevant portion of my Gruntfile:

express: {
  dev: {
    options: {
      script: 'server.js',
      args: [],
      output: "Application Server Ready"
    }
  }
},
watch: {
  express: {
    files: [
      'server.js',
      './lib/**/*.js'
    ],
    tasks: ['express:dev'],
    options: {
      spawn: false
    }
  }
}

Express server is stopped after `grunt express:dev`, not running in background

I know here were similar issues before, but I can't get what am I doing wrong: server is runt and then stopped.

app.js:

'use strict';
var app = express();
// ... usual express setup here, with views/routes/jade
app.listen(app.get('port'), function () {
    console.log('Test server on port ' + app.get('port'));
});

Gruntfile.js

        express: {
            dev: {
                options: {
                    script: 'app.js',
                    port: 3000
                }
            }
        }
    // ...
    // load all grunt tasks
    require('matchdep').filterDev('grunt-*')
        .forEach(grunt.loadNpmTasks);

Was trying with nospawn: true, get the same.
Then I run it:

$ grunt express:dev
Running "express:dev" (express) task
Starting background Express server
Test server on port 3000

Done, without errors.

Currently use: Node.js 0.10.24, Grunt 0.4.2, Express 3.4.7; OS X 10.9.
Running separately node app works fine as expected.

package.json

    "dependencies": {
        "express": "~3.4.7",
        "jade": "~1.0.2",
        "nconf": "*"
    },
    "devDependencies": {
        "grunt": ">=0.4.2",
        "grunt-contrib-copy": "*",
        "grunt-contrib-concat": "*",
        "grunt-contrib-uglify": "*",
        "grunt-contrib-jshint": "*",
        "grunt-contrib-less": ">=0.8.3",
        "grunt-contrib-watch": "*",
        "grunt-bytesize": "*",
        "grunt-express-server": "*",
        "grunt-mocha": "*",
        "grunt-open": "*",
        "matchdep": "*",
        "time-grunt": "*"
    }

'watch' task very slow to complete on server reload

Hi there,
I'm seeing some interesting behavior when trying to re-run the watch task after the express server stops and starts. On average, it takes 45 seconds for the task to complete before it is able to successfully watch any files that will change. Here's the output from my terminal

Running "express:dev" (express) task
Stopping Express server
Starting background Express server
website listening at http://localhost:8080

Running "watch" task
Completed in 47.560s at Thu Mar 19 2015 13:16:31 GMT-0700 (PDT) - Waiting...

The times to complete the watch task when first firing up the server, or changing css files are much much lower. Any ideas on what may be causing this?

Here's my Gruntfile:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    express: {
      options: {
        port: 8080
      },
      dev: {
        options: {
          script: 'app.js'
        }
      }
    },
    sass: {
      dist: {
        files: [{
          expand: true,
          cwd: 'assets/styles',
          src: ['*.scss'],
          dest: 'public/styles',
          ext: '.css'
        }]
      }
    },
    watch: {
      css: {
        files: '**/*.scss',
        tasks: ['sass'],
        options: {
          livereload: true,
        },
      },
      express: {
        files:  [ '**/*.js', '**/*.hbs' ],
        tasks:  [ 'express:dev' ],
        options: {
          spawn: false // for grunt-contrib-watch v0.5.0+, "nospawn: true" for lower versions. Without this option specified express won't be reloaded
        }
      }
    }

  });

  // Load the plugin that provides the "uglify" task.
  grunt.loadNpmTasks('grunt-contrib-sass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-express-server');

  // Default task(s).
  grunt.registerTask('server', ['express:dev', 'watch']);

};

and my app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs  = require('express-handlebars');

var app = express();
var routes = require('./routes')(app);
// view engine setup
app.engine('.hbs', exphbs({defaultLayout: 'main', extname: '.hbs'}));
app.set('view engine', '.hbs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

// Server
var server = app.listen(8080, function() {
  var host = server.address().address;
  var port = server.address().port;
  console.log('website listening at http://%s:%s', host, port);
});

module.exports = app;

Keepalive

I'm looking at the documentation and I don't see any way to specify that we should restart the server on crash (such as in a production setting). Is there any way to do this?

Add ability to forward arbitrary --nodejs options

For interpreters that call the node executable indirectly (e.g. CoffeeScript, IcedCoffeeScript), it would be nice to have the ability to forward arbitrary arguments like --debug-brk, --max-stack-size to node.

I saw that debug for CoffeeScript was added for issue #37 but I couldn't use it since I am using IcedCoffeeScript and the name of the command I'm using in options.cmd isn't 'coffee'.

Basically, this solves the problem in a more generic way than #37, allowing you to pass arguments other than debug and not only for 'coffee' executables.

Better CoffeeScript Example

Hi
It would be great if there was a more thorough explanation and example of how to use coffeescript in the app. I haven't been able to get it working.
Thanks

Server stops as soon as it starts

I'm having a weird issue when running a server on the background. Running it on the foreground seems to work fine, but when I run it on the background the server starts and stops as soon as it is started (so it's pretty much useless). This is the output I get when running grunt express:assets with the background option set to true:

Running "express:assets" (express) task
Starting background Express server

Done, without errors.
Stopping Express server

As I said, running it on the foreground seems to work (but I really need it to run on the background as I want to start/stop that server surrounding another grunt task), but there is another issue with running it on the foreground if I try to stop it, I get:

Running "express:assets:stop" (express) task
Starting background Express server
Fatal error: listen EADDINUSE

I don't get why this seems to try to start the server, as far as I can tell from the code on the task it should simply kill the server if it was started? Does anyone know what I might be doing wrong?

restart server based on Grunt Target

Hello and awesome project eric. 👍

I've a configuration like:

grunt.initConfig({
  express: {
    development: {
      options: {
        port: 8008,
        script: 'index.js'
      }
    },
    iodocs: {
      options: {
        port: 3000,
        script: 'node_modules/iodocs/app.js'
      }
    }
  },
  watch: {
    express: {
      files: ['middlewares/api/*.js', 'middlewares/*.js'],
      tasks: ['express:development'],
      options: {
        nospawn: true
      }
    },
    iodocs: {
      files: ['iodocs-config/apisites/*.json'],
      tasks: ['express:iodocs'],
      options: {
        nospawn: true
      }
    }
  }
});

grunt.registerTask('servers', 'express:development', 'express:iodocs', 'watch');

Reading in the issues i've noticed the express task kills the process ASAP it gets called again, but can this be tracked on a target basis?

In such way i could keep running multiple express servers, but i don't know if this is an aim of this project.

Stopping server on error

First of all, I want to thank you for the great work you've done on this grunt plugin.

I have livereload watching my server files. The problem is, if I introduce any error in the server code and save the file, the server reloads, throws an error, and then hangs. This is kind of annoying because then I have to close the command prompt out and CD back into the project folder to restart the server.

Is there a way to simply stop the server when an exception is thrown?

Cannot find module points to my webapp folder

Running "express:prod" (express) task
Starting background Express server

module.js:340
throw err;
^
Error: Cannot find module '/home/rttadi/Websites/testwebsite'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:245:9)

Done, without errors.

The grunt keeps throwing off this error while starting with express prod
I exactly copied the same code for registering and install express server.

server not stopping before restart when editing Gruntfile.js

Hi,

I have Grunt "watch" looking at some files and restarting Express if they get changed.

It all works seamlessly. For some weird reason though if the file edited is Gruntfile.js, grunt-express-server doesn't stop Express before relaunching when the express:dev task is triggered by grunt-watch and obviously it generates an EADDRINUSE error.

This is my grunt-watch configuration:

    watch: {
      options: {
        livereload: true
      },
      stylus: {
        files: ['<%= yeoman.app %>/styles/sections/*.styl'],
        tasks: ['stylus'],
        options: {livereload: false}
      },
      autoprefixer: {
        files: ['<%= yeoman.app %>/styles/*.css'],
        tasks: ['autoprefixer']
      },
      express: {
        files: [
          'app.js',
          'config/*.js',
          'controllers/*.js',
          'models/*.js',
          'Gruntfile.js'
        ],
        tasks: ['express:dev'],
        options: {spawn: false} // Without this option specified express won't be reloaded
      }

And this is my grunt-express-server configuration:

    express: {
      options: {
        port: process.env.PORT || 3000
      },
      dev: {
        options: {
          script: 'app.js'
        }
      },
      prod: {
        options: {
          script: 'app.js',
          node_env: 'production'
        }
      }
    }

The weird thing is that the problem ony happens with Gruntfile.js. If I modify, let's say, app.js or one of the controllers, the task correctly stops Express before reloading it.

Any thoughts?? Thanks!

Unable to abort process after server restart

I have a watch task that restarts the server whenever a file is changed. When the server first starts I can use the abort command ctrl+c in the command prompt to stop the server.

However, if I trigger the watch task to restart the server, I am no longer able to abort the process. Discovered this issue while investigating angular-fullstack/generator-angular-fullstack#52

After experimenting with the code I found that I could fix this by editing the stop method in the grunt-express-server and removing this line:

    process.removeAllListeners();

I think that it must be removing the listener for the abort command.

Bug: starting multiple instances causes error

We use grunt-express-server for automated Travis builds. Our tests start the same instance of an express server multiple times in a row. The following flow is the result:

  • express:test (waiting for output)
  • output detected and finished() -> done() is executed
  • express:test:stop
  • express:test (waiting for output)
  • doneFunction of grunt.util.spawn() executes finished() -> done() and the second server is not waiting for output anymore.

livereload does not seem to work with watch

I am using yeoman. I want to replace grunt-contrib-connect with this module, so I can run my express server. I probably just missed something, but I can't seem to get it to work like grunt-contrib-connect does with a static dir. The relevant parts of my grunt config look like this:

watch: {
  bower: {
    files: ['bower.json'],
    tasks: ['bowerInstall']
  },
  js: {
    files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
    tasks: ['newer:jshint:all'],
    options: {
      livereload: true
    }
  },
  jsTest: {
    files: ['test/spec/{,*/}*.js'],
    tasks: ['newer:jshint:test', 'karma']
  },
  styles: {
    files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
    tasks: ['newer:copy:styles', 'autoprefixer']
  },
  gruntfile: {
    files: ['Gruntfile.js']
  },
  livereload: {
    options: {
      spawn: false
    },
    files:  [
      'server.js',
      'modules/*.js',
      'models/*.js',
      'package.json',
      '<%= yeoman.app %>/{,*/}*.html',
      '.tmp/styles/{,*/}*.css',
      '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
    ],
    tasks:  [ 'express:livereload' ]
  },
  less: {
      files: ['<%= yeoman.app %>/styles/{,*/}*.less'],
      tasks: ['less:dist']
  }
},
express: {
  options: {
    script: 'server.js'
  },
  livereload: {
    options: {
    }
  },
  test: {
    options: {
    }
  },
  dist: {
    options: {
    }
  }
}

My task looks like this:

grunt.registerTask('serve', function (target) {
  if (target === 'dist') {
    return grunt.task.run(['build', 'express:dist:keepalive']);
  }

  grunt.task.run([
    'clean:server',
    'bowerInstall',
    'useminPrepare',
    'concurrent:server',
    'autoprefixer',
    'express:livereload',
    'watch'
  ]);
});

Background server won't start

Background server doesn't start when I'm running grunt express but when I run it from grunt watch it works perfectly.

Foreground server

Running "express:dev" (express) task
Starting foreground Express server
Development Mode
Express server listening on port 3000

Background server

Running "express:dev" (express) task
Starting background Express server
debugger listening on port 5858
Development Mode

Done, without errors.

Gruntfile

express: {
  dev: {
    options: {
      script: "app.js",
      node_env: "development",
      port: 3000,
      background: true,
      debug: true
    }
  }
},

//Watch
watch: {
  scripts: {
    files: ['scss/**/*.scss'],
    tasks: ['sass:dist']
  },
  express: {
    files:  ['i18n/**/*.json', 'helpers/**/*.js', 'routes/**/*.js', 'app.js'],
    tasks:  ['express:dev'],
    options: {
      spawn: false // Without this option specified express won't be reloaded
    }
  }
}

Option for nodeArgs

I was wondering what you thought of adding an option for an array of arguments that can be passed to the node process. Nodemon has a nodeArgs option for this that allows you to set options such as --debug-brk, --max-stack-size, and --expose-gc, in addition to --debug.

I'm particularly interested in using --debug-brk because it waits for a debugger to be connected before starting the execution of the server. This allows you to set breakpoints anywhere in your server, where as with the normal --debug argument you only can set breakpoints in places that are executed after the debugger has been connected, like routes.

Might be ignorance - but

Is there a ( probably obvious, I'm node-new ) way to have the express server reload when your server.js or similar file changes? I know nodemon is typically for this, but it seems within the watch context there might be a way in grunt-express-server?

Can't run 'express' and 'watch' at the same time...

Hi,

I am having trouble getting express and watch running concurrently. The idea is to restart the server anytime the code has changed.

First of all, the express task doesn't start a server on port 5000. Why is that?
And secondly, watch can't be started after express begins.

Here is my watch and express configs and the composite task:

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    ...

    watch: {
        client: {
            files: ['src/game/**/*', 'src/client/**/*'],
            tasks: ['devRebuild']
        },
        server: {
            files:  [ 'src/server/**/*', '!src/server/client/**/*' ],
            tasks:  [ 'express:server' ],
            options: {
                spawn: false
            }
        }
    },
    express: {
        options: {},
        server: {
            options: {
                script: 'src/server/server.js'
            }
        }
    }
});

// start develop
grunt.registerTask('devRebuild', ['clean', 'browserify:game_debug', 'stylus', 'copy']);
grunt.registerTask('dev', ['devRebuild', 'express', 'watch']);

And this is the server.js:

var pathUtils = require('path'),
    express = require("express"),
    bodyParser = require("body-parser"),
    app = express();

app.use( bodyParser.json() );

app.use( express.static( pathUtils.resolve( __dirname, "client" ) ) );

app.listen( process.env.PORT || 5000 );

And this is the output from running 'dev':

$ grunt dev

Running "clean:all" (clean) task
>> 0 paths cleaned.

Running "browserify:game_debug" (browserify) task

Running "stylus:compile" (stylus) task
File src/server/client/css/main.css created.

Running "copy:main" (copy) task
Created 2 directories, copied 2 files

Running "express:server" (express) task
Starting background Express server

I think the problem comes from the inability to actually start the server -> then it can detect a server started -> can't move on to the next grunt task. But why doesn't it start the server?

Thanks.

Watch stopping once express restarts

Originally reported here:

gruntjs/grunt-contrib-watch#252

I'm experiencing a problem where, when a file changes, it reloads express but then watch stops! What can cause watch to stop?

OK
>> File "server/controllers/home.js" changed.

Running "express:dev" (express) task
[D] Task source: /home/gwarner/sl2_express/node_modules/grunt-express-server/tasks/express.js
Stopping Express server
Starting background Express server

Running "watch" task
[D] Task source: /home/gwarner/sl2_express/node_modules/grunt-contrib-watch/tasks/watch.js
Completed in 0.047s at Sun Dec 15 2013 05:26:23 GMT-0700 (MST) - Waiting...

Done, without errors.

Archlinux, Node v0.10.23

Gruntfile:

'use strict';

module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-express-server');
    grunt.loadNpmTasks('grunt-contrib-watch');

    grunt.initConfig({
        watch: {
            express: {
                files:  [ 'server/**/*.js' ],
                tasks:  [ 'express:dev' ],
                options: {
                    spawn: false // Without this option specified express won't be reloaded
                }
            }
        },
        express: {
            options: {
                // Override defaults here
            },
            dev: {
                options: {
                    script: 'server.js'
                }
            },
            prod: {
                options: {
                    script: 'server.js',
                    node_env: 'production'
                }
            },
            test: {
                options: {
                    script: 'server.js'
                }
            }
        }
    });

    grunt.registerTask('server', [ 'express:dev', 'watch' ])

};

question: can you help me get this to work?

I've got a coffee task and a copy task that I use with watch. If I modify a .coffee file, the express server restarts just fine and works as expected, however if I modify, say, a .jade file - then I get this:

picture

As you can see, the express server stops running. I've tried to get it to work for a good two hours or so but I'm fairly new to Grunt and I don't know if I'm missing something or not - I just can't seem to get this to work right. Could you help me? 😄

This is my express task:

express: {
      options: {
        port: 3000,
        delay: 500,
        background: true
      },
      dev: {
        options: {
          script: './app.js'
        }
      },
      prod: {
        options: {
          script: './app.js',
          node_env: 'production'
        }
      }
    }

And my watch task:

watch: {
      options: {
        livereload: true // auto-refresh browser
      },
      css: {
        files: ['src/app/assets/styles/*.styl'],
        tasks: ['stylus']
      },
      js: {
        files: ['src/**/*.coffee'],
        tasks: ['coffee']
      },
      copy: {
        files: ['src/**/*.*', "!**/*.coffee", "!**/*.styl"],
        tasks: ['copy']
      },
      express: {
        files: ['**/*.js'],
        tasks: ['express:dev'],
        options: {
          nospawn: true
        }
      }
    }

background option cause the node consume too much CPU

If I set the background:true, the node will consume almost 35%~46% of my CPU.

my config:

express: {
    options: {
    port: 8080,
            debug: true,
            background: true,
            delay: 2000
        },
        dev: {
            options: {
                script: "app.js"
            }
        }
},

Server not starting in background

Hi,

I'm trying to use grunt-express-server, but when initially starting the server, it blocks the task-execution.

Inside watch:

        watch: {
            express: {
                files: 'backend/**/*',
                tasks: ['express:dev'],
                options: {
                    nospawn: true
                }
            }
        }

Task definition:

        express: {
            options: {

            },
            dev: {
                options: {
                    script: './backend/index.js',
                    nospawn: true
                }
            }
        }

Runner:

    grunt.registerTask('server', function (target) {
        if (target === 'dist') {
            return grunt.task.run(['open', 'connect:dist:keepalive']);
        }

        grunt.task.run([
            'clean:server',
            'compass:server',
            'livereload-start',
            'connect:livereload',
            'express:dev',
            'watch'
        ]);
    });

Now, when running 'grunt server' it goes through the defined tasks, until it reaches express:dev:

Console output:

Running "express:dev" (express) task
Starting background Express server

but it never reaches the watch task. When removing express:dev from the Runner, the watch task runs and calls express:dev - but only once, then it hangs again. Is there any special way I have to define my server? I'm using some wrapper functions, and inside those functions I use the listen() method. Might this cause the problems?

If you have some time I'd be very happy if you could help me.

Thanks for your help and kind regards
Marc

Help setting with watch

Hi, I'm just giving my first steps with grunt, and I have been trying to set express-server along with watch to run my simple index.html with no success, my current watch configuration is :

   watch: {

        options: {
            livereload: true,
        },

        scripts: {
            files: ['js/*.js'],
            tasks: ['concat', 'uglify'],
            options: {
                spawn: false,
              },
            },

      css: {
        files: '**/*.scss',
        tasks: ['compass']
      },
      html: {
        files: ['index.html'],
        tasks: ['htmlhint']
      }

  }

In the readme.md watch example you run a tasks for a dev sever that's pointing to "server.js" is that a node server I have to create? Any help as you may see is appreciated.

Coffeescript EADDRINUSE error

Gruntfile:

module.exports = (grunt) ->

  grunt.initConfig
    express:
      dev:
        options:
          script: "bin/www.coffee"
          opts:  ["node_modules/coffee-script/bin/coffee"]

    watch:
      express:
        files: [ "**/*.coffee" ]
        tasks: [ "express:dev" ]

  grunt.loadNpmTasks "grunt-express-server"
  grunt.loadNpmTasks "grunt-contrib-watch"

  grunt.registerTask "default", [ "express:dev", "watch"]

Starting the server works fine, but once a file is change, it seems like Grunt can't shut it down.

>> File "app.coffee" changed.
Running "express:dev" (express) task
Starting background Express server
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: listen EADDRINUSE
  at exports._errnoException (util.js:742:11)
  at Server._listen2 (net.js:1148:14)
  at listen (net.js:1170:10)
  at Server.listen (net.js:1245:5)
  at Function.app.listen (/home/michael/projects/doop/node_modules/express/lib/application.js:532:24)
  at Object.<anonymous> (/home/michael/projects/doop/bin/www.coffee:3:14)
  at Object.<anonymous> (/home/michael/projects/doop/bin/www.coffee:1:1)
  at Module._compile (module.js:449:26)

Stopping Express server
Completed in 0.865s at Fri Aug 08 2014 16:33:18 GMT-0500 (CDT) - Waiting...

More details: http://stackoverflow.com/questions/25212630/grunt-watch-coffee-express-eaddrinuse-error

server - too generic

I want to use this but I don't like that express-server requires the settings in another object called server that's unrelated to this. I already have something called server and it feels weird putting settings for express-server there.

I noticed this in the code:

grunt.config.get('server.script') 

Would something like this work?

grunt.task.current.options('script');

Server Static Files

I am using this with ember and would love to be able to in my grunt file add static folders to mount when I am in dev. grunt express can do this by adding bases to their config. Is there anything similar to this in grunt express server?

Thanks!

Cannot stop server

Hi,
I am experiencing issues with proper way of closing server.

Here is my watch config
watch: {
compass: {
files: ['<%= yeoman.app %>/styles/{,/}.{scss,sass}'],
tasks: ['compass']
},

        livereload: {
            files: [
                '<%= yeoman.app %>/*.html',
                '{.tmp,<%= yeoman.app %>}/styles/{,**/}*.css',
                '{.tmp,<%= yeoman.app %>}/scripts/{,*/,**/,**/**/}*.js',
                '<%= yeoman.app %>/templates/{,*/,**/,**/**/}*.hbs',
                '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp}',
                'test/spec/{,**/}*.js'
            ],
              options: {
                livereload: 35712
            }
        },

        express: {
            files:  [
                '<%= yeoman.dist %>/*',
                'server/*'
            ],
            tasks: ['express:prod:stop', 'express:prod'],
            options: {
                spawn: false
            }
        }
    };

Here is my grunt task for executing build, build server, opening browser and then watching for changes in dist folder.
grunt.task.run(['build', 'express:prod', 'open:prod', 'watch:express']);

I expect that every time build folder/server files are modified running server should stop and start again. I could see that during 'express:prod:stop' command inside stop Action of server.js 'server' variable is 'undefined' (line 114) so there is nothing to kill. Please suggest how to kill server/process that's already running.

Thanks

Livereload shutting down on changes

After run grunt server everything works and livereload is reloading the page but the express-server is stopped and there's no connection, meaning I have to refresh manually the page again. Do you have any fix for this ?

Task hangs if running in Coffeescript and there is a compile error

If I get any kind of compile error in my Coffeescript, the task hangs and never returns control to Grunt. I did a bit of debugging and found that if the output option is set, it only calls finished() if stdout has some output, but a compile error means only stderr will have output and finished() never gets called. In my own script I am getting around this by introducing a delay of 1, but this feels like not the right way to handle this. Would it make sense to introduce a change with a stderr.on('data') that does the same thing as the stdout.on('data')?

Here's the code snippet I'm referring to:

    if (options.output) {
      server.stdout.on('data', function(data) {
        var message = "" + data;
        var regex = new RegExp(options.output, "gi");
        if (message.match(regex)) {
          finished();
        }
      });
    }

Thanks @ericclemmons for your maintenance of this project and for supporting Coffeescript even though you've said you don't use it very much yourself. It's much appreciated.

configure debug port?

I am in a situation where I'm running two separate servers on my computer and they both want to use the same port (but can't) so I was hoping to change it for one of them... However, the only solution I've found it outside the scope of the gruntfile configuration, something like node --debug=7000 app.js (ie. http://stackoverflow.com/a/18911247).

Am I just missing something obvious, or is it possible to alter the default debug port from 5858 in the gruntfile?

Allow setting of arbitrary process.env variables

Hi Eric,

Thank you for this useful grunt task. Great work!

Currently, grunt-express-server supports overriding two environment variables, PORT and NODE_ENV. I feel it'd be nice to extend this and allow overriding of more variables, or allow setting of arbitrary variables.

My solution

Such overrides can be achieved by setting an env option object. The port and node_env options will be retained for backwards-compatibility, but they will be overriden if a different value is specified inside the env option. So basically something like this:

express: {
  options: {
    port: 3000,
    node_env: 'production',
    env: {
      DEBUG: 'server', //Sets a new variable
      PORT: 3001 //Overrides the value set using the port option above
    }
  }
}

Then, inside lib/server.js, I plan on extending the env object passed in to the call to grunt.util.spawn with the values supplied by the user. This can be implemented the way underscore.js implements extend().

If you agree, I'm willing to submit a pull request!

My use case

I was trying to get the grunt-express-server task to work with boilerplate code generated by the official express generator.

The boilerplate server requires an environment variable (DEBUG) to be set, for it to log anything out to the command line. You mention in the README that none of the subsequent tasks will be executed if nothing's logged out to the command line by the server.

I found no way of setting arbitrary environment variables with grunt-express-server's options, so I hacked this feature into my local copy.

Placeholders don't work with express 4

The bases and middleware are all placed at the end of express pipeline in version 4. This appears to be because the pipeline has been moved from the application variable "stack" to be part of the application's _router object.

References to server.stack in the util.js file need to be changed to server._router.task when working with express 4.

How to hide "deprecated" message?

Hey,

is there a way log all message from server to a log file? I set
logs: { out: 'file.log', err: 'file.log' }
but i get some "deprecated" messsages into my grunt output. Because it is async, i cannot read my grunt output very clearly. Is there a way to hide them?

Thanks,
Max

error with dir.servers

I'm trying to get this setup on my project and it seems that the 'dirs.server' in the temlate is undefined. Am I supposed to add that in somewhere?

Running "regarde" task
Warning: An error occurred while processing a template (dirs is not defined). Use --force to continue.

Aborted due to warnings.

Allow to add other environment variables

Currently, it is only possible to change the port and node_env environment variables.

I would like to set another environment variable.
In my case it is LIVERELOAD_PORT to be able to change the livereload port from the Gruntfile.js

Node runs relative to Gruntfile

I have a directory structure like this:

app
  |--client
  |--server
  |--app.js
Gruntfile.js

In the gruntfile, my script is configured as script: 'app/app.js' since effectively (correct me if I'm wrong) node is running from the position of the gruntfile. This means that I have to define static paths in my app relative to the Gruntfile like so:
app.use(express.static('app/client'));

Which means if I want to run my app elsewhere, not using grunt, I need to run node from one directory up and run node app/app.js.

In Gruntfile.js it would nice to be able to do something like

options: {
  cwd: 'app',
  script: 'app.js',
}

So paths in the app are relative to the app.js file, like so: app.use(express.static('client'));

Maybe I'm thinking of it in the wrong way, any help would be great.

rel 0.4.8 Object #<Object> has no method 'async' on exit

When I update my build to the newest 0.4.8 I get the following error when grunt is exiting and the server should be stopped.

When I fix the dependency to 0.4.7 it works again.

TypeError: Object #<Object> has no method 'async'
    at process.stop (/Users/retoblunschi/Documents/workspace/yp-backend/node_modules/grunt-express-server/tasks/lib/server.js:111:39)
    at process.EventEmitter.emit (events.js:117:20)
    at process.exit (node.js:707:17)
    at tryToExit (/Users/retoblunschi/Documents/workspace/yp-backend/node_modules/grunt/node_modules/exit/lib/exit.js:17:15)
    at Object.exit (/Users/retoblunschi/Documents/workspace/yp-backend/node_modules/grunt/node_modules/exit/lib/exit.js:34:3)
    at Object.task.options.done (/Users/retoblunschi/Documents/workspace/yp-backend/node_modules/grunt/lib/grunt.js:147:14)
    at Task.<anonymous> (/Users/retoblunschi/Documents/workspace/yp-backend/node_modules/grunt/lib/util/task.js:261:25)
    at Task.<anonymous> (/Users/retoblunschi/Documents/workspace/yp-backend/node_modules/grunt/lib/util/task.js:215:7)
    at null._onTimeout (/Users/retoblunschi/Documents/workspace/yp-backend/node_modules/grunt/lib/util/task.js:225:33)
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

thanks,
Reto

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.