Skip to content

Instantly share code, notes, and snippets.

@ssafejava
Last active January 4, 2017 04:08
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssafejava/8704372 to your computer and use it in GitHub Desktop.
Save ssafejava/8704372 to your computer and use it in GitHub Desktop.
// This is just an extension of https://github.com/gruntjs/grunt-contrib-connect#middleware
grunt.initConfig({
connect: {
server: {
options: {
middleware: function(connect, options) {
var middlewares = [];
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
var directory = options.directory || options.base[options.base.length - 1];
options.base.forEach(function(base) {
// Serve static files.
middlewares.push(connect.static(base));
});
// Make directory browse-able.
middlewares.push(connect.directory(directory));
// ***
// Not found - just serve index.html
// ***
middlewares.push(function(req, res){
for(var file, i = 0; i < options.base.length; i++){
file = options.base + "/index.html";
if (grunt.file.exists(file)){
require('fs').createReadStream(file).pipe(res);
return; // we're done
}
}
res.statusCode(404); // where's index.html?
res.end();
});
return middlewares;
},
},
},
},
});
@genediazjr
Copy link

[fixes]

var serveStatic = require('serve-static');

grunt.initConfig({
  connect: {
    server: {
      options: {
        middleware: function(connect, options) {
          var middlewares = [];
          if (!Array.isArray(options.base)) {
            options.base = [options.base];
          }
          var directory = options.directory || options.base[options.base.length - 1];
          options.base.forEach(function(base) {
            // Serve static files. (use serve-static instead)
            middlewares.push(serveStatic(base));
          });
          // Make directory browse-able. (not available on latest connect)
          // middlewares.push(connect.directory(directory));
          
          // ***
          // Not found - just serve index.html
          // ***
          middlewares.push(function(req, res){
            for(var file, i = 0; i < options.base.length; i++){
              // fixed missing index
              file = options.base[i] + "/index.html"; 
              if (grunt.file.exists(file)){
                require('fs').createReadStream(file).pipe(res);
                return; // we're done
              }
            }
            res.statusCode(404); // where's index.html?
            res.end();
          });
          return middlewares;
        },
      },
    },
  },
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment