• Stars
    star
    248
  • Rank 163,035 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

With grunt-contrib-watch

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

More Repositories

1

click-to-component

Option+Click React components in your browser to instantly open the source in VS Code
TypeScript
1,710
star
2

react-resolver

Async rendering & data-fetching for universal React applications.
JavaScript
1,650
star
3

grunt-angular-templates

Grunt build task to concatenate & pre-load your AngularJS templates
JavaScript
712
star
4

webpack-hot-server-example

Webpack Hot Module Replacement (HMR) Example with Express
JavaScript
367
star
5

polydev

Faster, route-centric development for Node.js apps with built-in Hot Module Replacement.
JavaScript
284
star
6

unique-selector

Given a DOM node, return a unique CSS selector matching only that element
JavaScript
260
star
7

terse-webpack

Simplified, fluent Webpack API with presets. Describe *what* your app needs, not *how*.
JavaScript
215
star
8

start-server-webpack-plugin

Automatically start your server once Webpack's build completes.
JavaScript
158
star
9

grunt-react

[DEPRECATED] Grunt task for compiling Facebook React's .jsx templates into .js
JavaScript
151
star
10

per-env

Clean up your package.json with per-NODE_ENV npm scripts
JavaScript
133
star
11

genesis-skeleton

Modern, opinionated, full-stack starter kit for rapid, streamlined application development.
CoffeeScript
106
star
12

if-env

Simplify npm scripts with `if-env ... && npm run this || npm run that`
JavaScript
97
star
13

node-recorder

Simple recording & replaying of HTTP requests for predictable development & testing.
TypeScript
97
star
14

jinja.js

Twig/Jinja/JinJS Client-Side Templating + jQuery Plugin
JavaScript
76
star
15

mdx-site

Static site generator powered by TypeScript, MDX, & React.
TypeScript
51
star
16

next.js-conf-2020

From Front-end to Full Stack with Amplify Framework
JavaScript
38
star
17

reload-server-webpack-plugin

Webpack plugin that automatically (re)starts your server between builds.
JavaScript
38
star
18

bookshelf-manager

Easily wire up models to APIs with supported for complex, nested saving.
JavaScript
34
star
19

universal-webpack

Library to greatly simplify running, watching, testing, & deploying universal apps with webpack.
JavaScript
34
star
20

medium-to-markdown

Convert Medium URLs to Markdown
JavaScript
30
star
21

mvc-to-react

Eric Clemmons' Space City JS 2015 talk – "Moving from MVC to React"
JavaScript
30
star
22

angular-github-demo

AngularJS demo application for HoustonJS
CSS
26
star
23

tech-2016-lightning-talks

10-minute lightning talks about Storybook, Styled Components, MobX, & Jest.
JavaScript
26
star
24

react.lazy-example

Testing out React.lazy (https://github.com/facebook/react/pull/13398)
JavaScript
24
star
25

hot-module

Reload changed files in Node *without* restarting the server (like nodemon/piping/etc.)
JavaScript
23
star
26

grunt-angular-modularize

Write AngularJS Modules Once. Build with RequireJS (AMD), Browserify (CommonJS), or simply concat.
JavaScript
23
star
27

github-semantic-version

Automated semantic version releases powered by Github Issues.
JavaScript
21
star
28

ECVagrantBundle

Symfony2 bundle to generate a working PHP5.3+ Vagrant environment
PHP
21
star
29

codelift

Visual Development for React, Next.js, & Tailwind CSS
17
star
30

de-pagify

Bookmarklet to enable "endless scroll" on popular sites
PHP
16
star
31

performant-3rd-party-widgets

Houston.js demo + slides for babel/webpack/react bundling & optimizations.
JavaScript
15
star
32

diez

Incredibly simple, Dependency Injection for isomorphic Javascript applications.
JavaScript
14
star
33

jest-storybook

Generate Jest snapshots from existing storybooks (similar to storyshots).
JavaScript
13
star
34

react-tooling-challenge

Competition to improve the tooling landscape for all React users.
13
star
35

eslint-config-future

ESLint Shareable Config for ES5/ES6/ES7 Javascript
JavaScript
12
star
36

wordpress-skeleton

[DEPRECATED] Dude, use https://github.com/genesis/wordpress/ !!
PHP
12
star
37

react-router-server-location

A React Router Location for universal apps.
JavaScript
12
star
38

start-cluster

Start a Node cluster by simply running `start-cluster`
JavaScript
11
star
39

graphql-context-services

GraphQL example using Context & Services
JavaScript
11
star
40

graphql-demo

Introduction to GraphQL (http://www.meetup.com/NodejsHouston/events/229815892/)
JavaScript
11
star
41

create-preact-pwa

"yarn create"-friendly version of preact-cli
JavaScript
9
star
42

grunt-verbosity

Adjust verbosity for individual grunt tasks
JavaScript
8
star
43

mootools-namespace

Allows Classes to specify namespace ("My.Fx.Accordion") and extend "Moo.Fx.Accordion", similar to Dojo.provide/require
JavaScript
6
star
44

tech-screen-template

Opinionated (but customizable!) template for tech screen interviews
TypeScript
6
star
45

express-hot-middleware

Simple way to enable hot-reloading in your Express applications.
JavaScript
6
star
46

babel-plugin-react-pure-to-class

https://github.com/gaearon/babel-plugin-react-transform/issues/57#issuecomment-167652102
JavaScript
5
star
47

graphql-mock-object

Easily prototype UIs with dynamic GraphQL objects
JavaScript
5
star
48

amplify-visor

Amplify Visor is a prototype GUI that customers run locally that streamlines the Amplify app-building experience – configuring & deploying Amplify visually, automatically installing dependencies, and reducing developer friction.
JavaScript
5
star
49

sync-github-pivotal

Bi-directional syncing between Pivotal Tracker & GitHub Issues
TypeScript
4
star
50

generator-genesis

Yeoman Generator for Genesis Skeleton
JavaScript
4
star
51

redux-reconnect

Redux hooks for React Resolver & Server-Side Rendering via "reconnect(...)"
3
star
52

create-graphql-app

Add an Amplify Function to `create-react-app`.
JavaScript
3
star
53

begin-react-app

Begin app
JavaScript
2
star
54

react-zones-example

Can Zones magically simplify SSR? http://blog.kwintenp.com/how-the-hell-do-zones-really-work/
2
star
55

vagrant-php

Instantly setup & launch PHP5.x Vagrant machine
PHP
2
star
56

vagrant-shim

Transparently run commands through your Vagrant VM.
PHP
2
star
57

sublime-typescript

DEPRECATED - Use Microsoft's official plugin instead!
2
star
58

ericclemmons

MDX
2
star
59

ericclemmons.com

TypeScript
2
star
60

amplify-flow

Native app for GitHub issue management for Amplify JS
TypeScript
2
star
61

ericclemmons.github.io

Official (Dynamic) Website of Eric Clemmons
CSS
2
star
62

zend-memcached-namespaced

Zend_Cache_Backend_Memcached with Namspace support for clearing specific keys
1
star
63

react-shared-state

Simple <SharedState> component to wrap your app & auto-inject Redux & MobX stores.
1
star
64

angular-lazy-load

Experimenting with lazy-loading angular.modules
JavaScript
1
star
65

microbundle-monorepo

Having an issue with CSS not being extracted when part of a monorepo
CSS
1
star
66

flummox-parent-promise

JavaScript
1
star
67

css-system

JavaScript
1
star
68

genesis-skeleton.com

Official website of Genesis Skeleton
CoffeeScript
1
star
69

mobx-resolver

Prefect MobX data dependencies before rendering React components.
1
star
70

redux-devtools-visual

Easily scrub through a visual history of your application, branch, and repeat!
1
star
71

amplify-js-canary

Canary releases for https://github.com/aws-amplify/amplify-js
1
star
72

amplify-js-issues-4506

https://github.com/aws-amplify/amplify-js/issues/4506
HTML
1
star
73

capistrano-svn-deployment

Example deployment script using Python & Capistrano for PHP apps in SVN
Python
1
star
74

ng-gitboard

Github dashboard powered by Angular.
JavaScript
1
star
75

redux-server

Redux-powered server & middleware for predictably handling requests with immutable responses.
1
star
76

ericclemmons.github.com

Office (Static) Website of Eric Clemmons
1
star