Skip to content

Instantly share code, notes, and snippets.

@ronsims2
Created January 31, 2016 17:22
Show Gist options
  • Save ronsims2/5da6b2b9d141b455b56d to your computer and use it in GitHub Desktop.
Save ronsims2/5da6b2b9d141b455b56d to your computer and use it in GitHub Desktop.
A simple web server that allows you to specify a JSON file based on a URL param.
//https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/
var myPort = 8080;//Set pot to one not used on your box
var fs = require('fs')
var http = require('http');
console.log('Starting server...')
var server = http.createServer(function(req, resp){
console.log('Request received. ');
//get url param and change file based on param or url
var param = req.url.split('?');
if (param.length > 1) {
param = param[1].split('=');
if (param.length > 1) {
param = param[1];
}
}
var fileLoc = '';//Map your params to files here
switch(param){
case 'bar':
fileLoc = 'C:/Projects/nodebin/bar.json';
break;
case 'baz':
fileLoc = 'C:/Projects/nodebin/baz.json';
break;
default:
fileLoc = 'C:/Projects/nodebin/foo.json';
break;
}
fs.readFile(fileLoc, 'utf8', function(err, data) {
if (err) {
consoole.log(err);
}
else {
console.log(data);
resp.statusCode = 200;
resp.setHeader('Content-Type', 'application/json');
resp.write(data);//Echo JSON
resp.end();
}
});
}).listen(myPort);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment