X

Node.js

Create A Node Server

May 4, 2020

/*

Require modules, declare variables

*/

Require the http module, this module is used to handle all things related to the http protocol. In this post we'll be looking at just the server, but in the future I'll be checking out making a request to other servers, connecting status messages to the response & other useful things.

Declare the port variable. This will be the port that our server is listening on.

/*

Create the server

*/

I'm going to use the http.createServer method which takes a callback function as it's argument. The callback function takes two parameters, the request and response objects. The request object is the request coming into the server. The response object is your server's response to the request. I'm going to console.log some text in the callback function to see a message when I turn the server on.

/*

Listen to request

*/

Call the server.listen method. The server.listen method takes the port that we want to listen on and a callback that we can run some code as it's arguments. Use another console.log to see if our server is listening.

Run the terminal and call node {filename} in the file directory.
That's it. Our server is up & running.

About the Author

Christopher Howard

Chris is a Javascript developer with a minor in UI design. He values programming in vanilla code. Fill out the form below to contact him.