Last active
October 15, 2017 10:06
-
-
Save szxp/09cac3ef8f14f2336e62a1399cc8e19e to your computer and use it in GitHub Desktop.
Node.js static file server over HTTPS
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
// Serves static files from the www directory over HTTP | |
// Usage: node serveStatic.js | |
// generate SSL keys for supporting HTTPS | |
// openssl genrsa -out server-key.pem 1024 | |
// openssl req -new -key server-key.pem -out server-csr.pem | |
// openssl x509 -req -in server-csr.pem -signkey server-key.pem -out server-cert.pem | |
"use strict"; | |
var fs = require('fs'); | |
var path = require('path'); | |
//var https = require('https'); | |
var http = require('http'); | |
var mime = require('mime'); | |
var url = require('url'); | |
var staticBasePath = './www'; | |
var staticServe = function(req, res) { | |
// Website you wish to allow to connect | |
res.setHeader('Access-Control-Allow-Origin', '*'); | |
// Request methods you wish to allow | |
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); | |
// Request headers you wish to allow | |
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type'); | |
// Set to true if you need the website to include cookies in the requests sent | |
// to the API (e.g. in case you use sessions) | |
res.setHeader('Access-Control-Allow-Credentials', true); | |
if (req.url === "/") { | |
req.url = req.url + "index.html"; | |
} | |
var filename = path.resolve(staticBasePath); | |
var url_parts = url.parse(req.url); | |
filename = path.join(filename, url_parts.pathname); | |
fs.exists(filename, function (exists) { | |
if (!exists) { | |
res.writeHead(404, { | |
"Content-Type": "text/plain" | |
}); | |
res.write("404 Not Found\n"); | |
res.end(); | |
console.log('%s %s', res.statusCode, req.url); | |
return; | |
} | |
fs.readFile(filename, "binary", function (err, file) { | |
if (err) { | |
console.log('Error: %s', err); | |
res.writeHead(500, { | |
"Content-Type": "text/plain" | |
}); | |
res.write("Server error\n"); | |
res.end(); | |
console.log('%s %s', res.statusCode, req.url); | |
return; | |
} | |
var type = mime.getType(filename); | |
res.writeHead(200, { | |
"Content-Type": type | |
}); | |
res.write(file, "binary"); | |
res.end(); | |
console.log('%s %s', res.statusCode, req.url); | |
}); | |
}); | |
}; | |
//var server = https.createServer({ | |
// key: fs.readFileSync('server-key.pem'), | |
// cert: fs.readFileSync('server-cert.pem') | |
//}, staticServe); | |
var server = http.createServer(staticServe); | |
var port = 8080; | |
console.log('Listening on port %s', port); | |
server.listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment