Setting up an alias directory for a Grunt connection server

I have some folders in my source that I want to serve with connect via a grunt task. My folder structure looks like this:

  • /
  • / CCI
    • index.jade
    • / styles
      • main.css
  • /distance
    • index.html
  • /documents
    • index.html

My grunt config looks something like this:

grunt.initConfig({
    connect: {
        options: {
            port: 8080,
            hostname: '0.0.0.0',
            livereload: 35729
        },
        app: {
            options: {
                middleware: function (connect) {
                    return [
                        connect.static(require('path').resolve(pkg.paths.dist)),
                        connect.static(require('path').resolve(pkg.paths.src)),
                        connect.static(require('path').resolve(pkg.paths.docs))
                    ];
                }
            }
        },
    }
})

      

Firing the server, and visiting http://localhost:8080/

will give me the index.html

file from dist

- which was compiled from index.jade

, which belongs to main.css

, which is dutifully serviced from.This is src

all great, and works great.

Now I want to access the index.html

file from docs

but on the url alias - so http://localhost:8080/mycustomurl

. I don't want to put my documents in a subfolder, I just want to set up a connection to serve urls that match mycustomurl

from the directory docs

.

How can I change my configuration to achieve this?

+3


source to share


1 answer


Use dedicated middleware. The option middleware

expects a function that returns an array of mediators.

custom_middleware: {
  options: {
    middleware: function(connect, options, middlewares) {
      return [connect.static(require('path').resolve(pkg.paths.dist)),
              connect.static(require('path').resolve(pkg.paths.src)),
              function (req, res, next) {
                if (req.url !== '/custom/url') {
                  next();
                  return;
                }
                // res.sendFile(pkg.paths.docs + '/index.html');
                // you can access the "anything.html" by parsing the req.url
                var file = req.url.split('/');
                file = file[file.length-1];
                res.sendFile(pkg.paths.docs + file);
              }
      ];
    }
  }
}

      



For more configuration options, see the Gruntfile example .

+2


source







All Articles