Tag Archives: webserver

Creating and running a simple Node.js server

12 Jun
Building a server in JavaScript?

If you’re using lots of JavaScript for the client-side of your app, it may make sense for you to also use JavaScript for the server. Such is the convenience of Node.js.

In this article we’ll go over all the setup and code needed to get a Node.js server loading an index.html file from localhost into your web browser.

What you’ll need

Install Homebrew if you don’t already have it.

Run brew install node in your Terminal. This will install both node andnpm.

Now, run npm install express ––save to install Express.

A simple server.js file

Here’s is all the code you’ll need to serve your index.html page when you visit localhost:8000 in your web browser. Save this server.js file in the same directory as your index.html file.

/* *****************
 * Require Imports *
 * *****************/

var express = require('express');
var path = require('path');

/* ***********************
 * Initialize Middleware *
 * **********************/

// Instantiate the express object
var app = express();

// Use the static assets from the same directory as this server.js file
app.use(express.static(path.resolve("./")));

/* **************
 * GET Requests *
 * **************/

// index.html
app.get('/', function(req, res) {
  res.sendFile('index.html');
});

/* ******************
 * Start the server *
 * ******************/

var port = process.env.PORT || 8000;

var server = app.listen(port, function() {
  console.log('Listening on port:', port);
});

Running the Node.js server
Now, execute the command node server.js in your Terminal to run the JavaScript file that will serve up our index.html page.

Finally, open your browser and navigate to localhost:8000.

And you are done…..