First Node.js Sample – Hello World

Yeah…it’s “Hello World” again.

You don’t really need to put your javascript in specify folder; so you can just create a new folder and put everything inside. Because I used nvm to install Node.js before, so I put my demo files inside ~/.nvm


// hello.js
var http = require('http');
    http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello, World!\n');
}).listen(8124);
console.log('Server running at http://localhost:8124/');

In here, we will require http package because we want to see the page in our browser, not just a simple console log message.

We use http.creatServer to create a new web object, and it will listen port 8124. In this case, I just use my own Mac, so I didn’t provide hostname. But if you are using some dev machine, you can provide your hostname or ip in listener.


http.createServer(function (req, res) {
    ....
}).listen(8124, 'hostname/ip');

If you already finished it, please run command:


$ node http.js
Server running at http://localhost:8124/
_

And go to http://hostname:8124/, you will see the result like this:

Node.js Hello World

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s