Skip to content

Instantly share code, notes, and snippets.

@IskenHuang
Last active December 26, 2015 20:39
Show Gist options
  • Save IskenHuang/7210042 to your computer and use it in GitHub Desktop.
Save IskenHuang/7210042 to your computer and use it in GitHub Desktop.
grunt-contrib-connect middleware redirect function

GOAL

grunt-contrib-connect middleware redirect function. easy to use make fake api for front-end. This sample used yeoman generator gruntfile.

how to use

  • download redirect.js to project root.
  • edit Gruntfile.js
var redirect = require('./redirect');

...
...


connect: {
    options: {
        port: 9000,
        // change this to '0.0.0.0' to access the server from outside
        hostname: '0.0.0.0'
    },
    livereload: {
        options: {
            middleware: function(connect) {
                return [
                    lrSnippet,
                    mountFolder(connect, '.tmp'),
                    mountFolder(connect, 'app'),
                    redirect('api')
                ];
            }
        }
    }
},
  • the redirect with 3 arguments. rootDir is fake api root folder. indexFile is default file. headers is response header for example:
/app
    ...

/api
    /user
        index.json
        list.json
...

/Gruntfile.js
...
  • run grunt server
    • access /user will response /api/user/index.json
    • access /user/list.json will response /api/user/list.json
var fs = require('fs'),
url = require('url');
module.exports = function(rootDir, indexFile, headers) {
'use strict';
indexFile = indexFile || 'index.json';
var defaults = {
'Content-Type': 'text/plain'
};
console.log('--------------------------------------------------');
console.log('redirect = ', rootDir, ' || indexFile = ', indexFile);
if(headers){
console.log('headers = ', headers);
}else{
headers = {};
}
console.log('--------------------------------------------------');
// setup default values
for(var i in defaults) {
if(!headers[i]) {
headers[i] = defaults[i];
}
}
return function(req, res, next) {
var path = url.parse(req.url).pathname,
filePath = './' + rootDir + path + '/' + indexFile;
if(path.match(/\..{3}/g)){
filePath = './' + rootDir + path;
}
fs.readFile( filePath, function(error, buffer) {
if (error){
return next(error);
}
// set content length
headers['Content-Length'] = buffer.length;
var resp = {
headers: headers,
body: buffer
};
res.writeHead(200, resp.headers);
res.end(resp.body);
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment