Last active
May 14, 2016 01:29
-
-
Save muratcorlu/5803655 to your computer and use it in GitHub Desktop.
Simple connect middleware for simulating url-rewriting for grunt connect servers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'), | |
url = require('url'); | |
module.exports = function (rootDir, indexFile) { | |
indexFile = indexFile || "index.html"; | |
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('./' + rootDir + '/' + 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); | |
}); | |
}); | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Usage example | |
module.exports = function(grunt) { | |
var urlRewrite = require('grunt-connect-rewrite'); | |
// Project configuration. | |
grunt.initConfig({ | |
connect: { | |
server: { | |
options: { | |
port: 9001, | |
base: 'build', | |
middleware: function(connect, options) { | |
// Return array of whatever middlewares you want | |
return [ | |
// redirect all urls to index.html in build folder | |
urlRewrite('build', 'index.html'), | |
// Serve static files. | |
connect.static(options.base), | |
// Make empty directories browsable. | |
connect.directory(options.base) | |
]; | |
} | |
} | |
} | |
} | |
}); | |
grunt.loadNpmTasks('grunt-contrib-connect'); | |
grunt.registerTask('default', ['connect']); | |
}; |
I'm new to Grunt and I got the same prolem as mrdavenz
For those who can't get this script to work:
Place the grunt-connect-rewrite.js file in your bower_components folder.
The 'require('grunt-connect-rewrite');' is referencing the script there. You can then use it in your grunt tasks
Shows me an error "Object build has no method 'initConfig' Use --force to continue."
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is there anything else required to get this working, when I implemented this GIST, the grunt script runner kicked up the error ">> Error: Cannot find module 'grunt-connect-rewrite'"