Setting up a local NodeJS server


To start, Macs can install node from the command line.

brew install node

Creating the Server Locally

In our Javascript editor of choice, we need to import the ‘http’ module first. Importing modules is similar to having parts of other files available for us to access. The require() function allows us to import by passing stuff of interest into the parentheses. Conveniently, the http module comes with node so we can refer to it by the string ‘http’. Store a reference to the module so we can easily call the module’s methods.

var httpModule = require(‘http’);

Use the createServer() method located on the module to create the server and store the reference to the server in a variable. If you plan on handling any requests to your server, pass in your request handler function to createServer.

// Haven't defined the request handler function yet.
// Let's call it myRequestHandler for now and code it later.
var server = httpModule.createServer(myRequestHandler);

Listening to the server is easy. Call the listen() method on the server and give it 2 arguments: port number and ip number.

var port = 3000;

// refers to localhost, the server runs on your computer.
var ip = ‘127.0.0.1’;
server.listen(port, ip);

Handling Basic Requests

Functions that handle requests are just called request-handlers they do exactly what you think. They have 2 parameters: the request object and response object (order matters). Those 2 objects are passed to the request handler by Node, but it doesn’t know what to do with them.

var myRequestHandler = function(request, response) {
// Tell node how to handle the request and response here.
};

GET Requests (fetching data)

GET requests are sent to the server when you want the server to give you information.

The request object has a property called “method” on it that changes it’s value depending on the type (get, post, put, delete) of request coming in.

var myRequestHandler = function(request, response) {
if (request.method === "GET") {
// do stuff for GET requests
}
};

Let’s just log to the console when the server hears a get request:

var myRequestHandler = function(request, response) {
if (request.method === "GET") {
console.log('heard a GET request');
// anything else you want
}
};

POST Requests (receiving data)

POST requests are sent to the server when you want to give information to the server.

POST requests are a bit different than GET requests. During a POST request there are 2 events emitted that we can act upon: the “data” and “end” events. When data is sent to the server, it is split into chunks. The data event is emitted whenever the server receives one of these chunks. Once all the chunks have been received, the end event is emitted. So, we want to collect all these chunks as they come in so we can translate (parse) them into something readable (like JSON).

We can call the on() method on the request object to listen to the events. on() takes 2 parameters: the name of the event you are listening for and a function to execute when the event is heard. The callback function is passed the chunks so we can do stuff with them.

request.on("data", function(chunk) {
// do stuff with chunk
});

Generally the most useful thing to do with the chunks is to combine them to get the data you were sent. Let’s collect the chunks in a variable.

// chunks are strings
var collectedChunks = "";
request.on("data", function(chunk) {
collectedChunks += chunk;
});

Once all the chunks have contacted the server the end event is emitted to tell us no more chunks are coming. Let’s console.log the collected chunks and send a response back to the sender. This tells them that the server heard the POST request.

request.on("end", function() {
console.log(collectedChunks);
response.end();
});

And the completed code, saved as server.js:

// server.js
var httpModule = require('http');
var port = 3000;
var ip = '127.0.0.1';

var myRequestHandler = function(request, response) {
  if (request.method === "GET") {
console.log('heard a GET request');
} else if (request.method === "POST") {
var collectedChunks = "";
    request.on("data", function(chunk) {
collectedChunks += chunk;
});
    request.on("end", function() {
console.log(collectedChunks);
response.end();
});
}
};
var server = httpModule.createServer(myRequestHandler);
server.listen(port, ip);
console.log('server listening on port 3000');

Run the Server

From the terminal, execute node with your server file (make sure you are in the same directory):

node server.js
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.