Effective DevOps with AWS
上QQ阅读APP看书,第一时间看更新

Running a node.js Hello World.

Now that node is installed, we can create a simple Hello World application. Here is the code for creating this:

var http = require("http")

http.createServer(function (request, response) {

    // Send the HTTP header
    // HTTP Status: 200 : OK
    // Content Type: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'})
    // Send the response body as "Hello World"
    response.end('Hello World\n')
}).listen(3000)

// Console will print the message
console.log('Server running')

Feel free to copy this into a file, or if you want to save time, download this from GitHub:

[ec2-user@ip-172-31-22-234 ~]$ wget http://bit.ly/2vESNuc -O /home/ec2-user/helloworld.js
--2017-01-31 23:58:20--  http://bit.ly/2vESNuc
Resolving bit.ly (bit.ly)... 69.58.188.39, 69.58.188.40
Connecting to bit.ly (bit.ly)|69.58.188.39|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://raw.githubusercontent.com/EffectiveDevOpsWithAWS/code-snippets/master/helloworld.js [following]
--2017-01-31 23:58:21--  https://raw.githubusercontent.com/EffectiveDevOpsWithAWS/code-snippets/master/helloworld.js
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 199.27.76.133
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|199.27.76.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 389 [text/plain]
Saving to: '/home/ec2-user/helloworld.js'
    
/home/ec2-user/helloworld.js      100%[=============================================================>]     389  --.-KB/s   in 0s
    
2017-01-31 23:58:21 (100 MB/s) - '/home/ec2-user/helloworld.js' saved [389/389]
    
[ec2-user@ip-172-31-22-234 ~]$  

And now, in order to run the Hello World application, we are simply going to run the following code:

[ec2-user@ip-172-31-22-234 ~]$ node helloworld.js
Server running  

If everything goes well, you can now open this in your browser http://your-public-dns-name:3000, in my case, http://ec2-54-88-134-38.compute-1.amazonaws.com:3000, and see the result, as follows:

We will now stop the execution of the Hello World web application with Ctrl + C in your Terminal window.