Created
February 24, 2017 18:50
-
-
Save federicofazzeri/b5ea6d1a7359b55b300026838fbc296d to your computer and use it in GitHub Desktop.
A Grunt task with no dependencies to serve static files (optionally set port and staticBasePath: server: { port: 3300, staticBasePath: './build' })
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
module.exports = function(grunt) { | |
var config = { | |
watch: {}, | |
server: {} | |
}; | |
grunt.initConfig(config); | |
grunt.loadNpmTasks('grunt-contrib-watch'); | |
grunt.loadTasks('tasks'); | |
grunt.registerTask('default', ['server', 'watch']); | |
}; |
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
module.exports = function(grunt) { | |
var fs = require('fs'); | |
var path = require('path'); | |
var http = require('http'); | |
grunt.registerTask('server', 'static file development server', function(){ | |
//set default params if not configured in Gruntfile | |
var port = grunt.config.get('server.port') || 3000; | |
var staticBasePath = grunt.config.get('server.base') || './'; | |
//create the server | |
var httpServer = http.createServer(function(req, res) { | |
var filePath, stream; | |
//serve index.htm | |
if(req.url === '/') { | |
req.url = 'index.html'; | |
} | |
//get the file path | |
filePath = path.join(path.resolve(staticBasePath), req.url); | |
//create a read stream | |
stream = fs.createReadStream(filePath); | |
// handle errors | |
stream.on('error', function(error) { | |
res.writeHead(404, 'Not Found'); | |
res.end(); | |
}); | |
// file is ok | |
res.statusCode = 200; | |
//attach the file stream to the response | |
stream.pipe(res); | |
}); | |
httpServer.listen(port, function(){ | |
console.log('listening on port http://localhost:' + port); | |
}); | |
return httpServer; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment