Node Server thing - JamesDansie/data-structures-and-algorithms GitHub Wiki
Node Server
Author: James Dansie
Sourced from; https://howtonode.org/deploy-blog-to-heroku
First we'll make a server using node with the following code;
var http = require("http");
then
http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("It's alive!"); response.end(); }).listen(3000);
Then call it with;
node server.js
Then log into heroku
heroku login
Now declare some variables;
var http = require("http"); var fs = require("fs"); var path = require("path"); var mime = require("mime");
Now make a json
{ "name" : "blog", "version" : "0.0.1", "description" : "My minimalistic blog", "dependencies" : { "mime" : "~1.2.7" } }
To install dependencies;
npm install
To make our 404 page fail;
function send404(response) { response.writeHead(404, {"Content-type" : "text/plain"}); response.write("Error 404: resource not found"); response.end(); }
To send the actual page we neeed;
function sendPage(response, filePath, fileContents) { response.writeHead(200, {"Content-type" : mime.lookup(path.basename(filePath))}); response.end(fileContents); }
To get access to the file path;
function serverWorking(response, absPath) { fs.exists(absPath, function(exists) { if (exists) { fs.readFile(absPath, function(err, data) { if (err) { send404(response) } else { sendPage(response, absPath, data); } }); } else { send404(response); } }); }
Finally we're creating the http server;
`var server = http.createServer(function(request, response) { var filePath = false;
if (request.url == '/') { filePath = "public/index.html"; } else { filePath = "public" + request.url; }
var absPath = "./" + filePath; serverWorking(response, absPath); });`
Finally, to run this bastard;
http.createServer(<some code here>).listen(3000) var port_number = server.listen(process.env.PORT || 3000);
Remember to create some content, and then to run it locally;
node server.js