Skip to content

Instantly share code, notes, and snippets.

@marfarma
Forked from muratcorlu/grunt-connect-rewrite.js
Last active December 26, 2015 09:19
Show Gist options
  • Save marfarma/7128987 to your computer and use it in GitHub Desktop.
Save marfarma/7128987 to your computer and use it in GitHub Desktop.
var fs = require('fs'),
url = require('url');
module.exports = function (rootDir, indexFile) {
indexFile = indexFile || "index.html";
rootDir = rootDir || '';
var rootPart = rootDir.length > 0 ? rootDir + '/' : '';
return function(req, res, next){
var path = url.parse(req.url).pathname;
fs.readFile('./' + rootDir + path, function(err, buf){
if (!err) return next();
fs.readFile('./' + rootPart + indexFile, function (error, buffer) {
if (error) return next(error);
resp = {
headers: {
'Content-Type': 'text/html',
'Content-Length': buffer.length
},
body: buffer
};
res.writeHead(200, resp.headers);
res.end(resp.body);
});
});
}
};
// Usage example
module.exports = function(grunt) {
var urlRewrite = require('grunt-connect-rewrite');
// Project configuration.
grunt.initConfig({
connect: {
server: {
options: {
port: 3000,
base: '.',
middleware: function(connect, options) {
// Return array of whatever middlewares you want
return [
// redirect all urls to index.html in '.' folder
urlRewrite(),
// Serve static files.
connect.static(options.base),
// Make empty directories browsable.
connect.directory(options.base)
];
}
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default', ['connect']);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment