How to create a server in Node.js without using Express
Have you ever wondered how to spin up a server using only Node? Well, look no further.
This article will show you a “Hello World” example of a server written only using Node. I will try to briefly explain the code and then show you some variations on the code.
Let’s dive right in.
This piece of code spins up a server that listens on localhost:3000 and prints “suh dude” to the screen. Look familiar?
This code is nearly identical to how one might write their first Express server.
The first line of code requires the built in “http”-module in Node. This module will allow us to create a server using the built in method “createServer”. We do this on line 5 and then define the response — in our case sending back a status of 200 and the string “suh dude”. We now have a server, but our server isn’t able to interact since it is not listening.
On line 10 we tell the server to listen to our specified hostname and port.
Now, if we run “node server.js” in our terminal we see the following in our terminal:
Great success. We now have a server! :)
Now for the variations of the code above. Let’s take a look at some different examples…
In the above example I omitted the port. The listen method requires a port to specified. What if I omitted the hostname, will it default to something we can use and spin up a server for us? Let’s see….
Ok! So a port is required but a hostname is not. Could we change the order of how we’re passing in the port and hostname.
I’ll let you take a guess on this one. Will there be a server?
Turns out example 1 does not work, but example 2 does!
Last challenge coming up. Will there be server?
What did you think? Turns out all three examples spins up a server!
Thanks for reading and have fun creating servers.