Created
December 27, 2016 17:47
-
-
Save JohnEarnest/34b027c62eaf3c768b8963a4daa70457 to your computer and use it in GitHub Desktop.
A CORS-aware read/write HTTP server in Node.js
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
//////////////////////////////////////////////////////////////////////////// | |
// | |
// Node.js HTTP file server example. | |
// | |
// Serves documents via GET requests with CORS headers and (if enabled) | |
// additionally permits writes via POST requests. | |
// | |
// Before using, PLEASE be aware of the security risks associated with | |
// running a server like this on publicly accessible machines! | |
// | |
//////////////////////////////////////////////////////////////////////////// | |
var BASE_DIR = '/path/to/files'; | |
var PORT = 10101; | |
var ENABLE_WRITE = true; | |
var http = require('http'); | |
var url = require('url'); | |
var fs = require('fs'); | |
http.createServer(function(request, response) { | |
var path = url.parse(request.url).pathname; | |
var verb = request.method; | |
console.log(verb + ": " + path); | |
response.setHeader('Access-Control-Allow-Origin', '*'); | |
if (verb == 'GET') { | |
try { | |
var file = fs.readFileSync(BASE_DIR + path); | |
response.writeHead(200); | |
response.end(file); | |
} | |
catch(error) { | |
console.log('rejected; file not found.'); | |
response.writeHead(404); | |
response.end(); | |
} | |
return; | |
} | |
if (verb == 'POST' && ENABLE_WRITE) { | |
var body = ''; | |
request.on('data', function(x) { body += x; }); | |
request.on('end', function() { | |
try { | |
fs.writeFileSync(BASE_DIR + path, body); | |
response.writeHead(200); | |
response.end(); | |
} | |
catch(error) { | |
console.log('rejected; invalid path.'); | |
response.writeHead(400); | |
response.end(); | |
} | |
}); | |
return; | |
} | |
response.writeHead(400); | |
response.end(); | |
}).listen(PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment