This first node.js server will run a http server port listener and allow you to connect to the port listener from a web browser to test your node.js server.

Create a hello-server.js file with Sublime text editor with the following

// hello-server.js

const http = require('http') 
const port = 4200

const requestHandler = (request, response) => { 
 console.log(request.url)
 response.end('Hello Node.js Server!')
}

const server = http.createServer(requestHandler)

server.listen(port, (err) => { 
 if (err) {
 return console.log('something bad happened', err)
 }

 console.log(`server is listening on ${port}`)
})

Upload the file to the node.js server then go to the same directory in a terminal window. Run the server with the command

node hello-server.js

You can then point a web browser to http://aws.mydomain.com:4200/
Your browser will receive a page

Hello Node.js Server!

Your terminal window will respond with the following results

server is listening on 4200
/
/favicon.ico

The / is the path of the page requested and the /favicon.ico is requested by the browser as well. To end the terminal window server be sure to use CTRL-C if by accident you don’t close it properly you will leave the process running locking the port. A future node.js hello-server.js command will result in an EADDRINUSE error. To release the processes do the following

ps aux | grep node

this will give you a list of active processes. the PID number is the first column in the list. You can then kill each PID with the following command

kill -9 PID

In a later post we will create an actual port listener that can respond to a real world situation with multiple requests and create an asynchronous port listener.

Advertisements