In this tutorial, I will tell you how you will start with your first application in Node.js. This post is very important for you when you think to start with Node.js.
You will know numerous Node.js concepts so it will be good idea for you to read again and again to make sure you have understood it properly.
In this post, we will create a real Node.js app from scrach.
In Node.js, you need to register some callback and import some required module. To import required module, we use the require
directive to load Node.js modules.
In this step, first load the required module and in this example we will load http library to call Node.js library that allow us to create a web server.
var http = require('http');Step 2: Create Server
In first step i have created http instance that represents the javascript object that will use to call http.createServer()
method to launch web server.
var server = http.createServer();
We have launched the web server and save this in server variable.
- var http = require('http');
- var server = http.createServer(function(req, res) {
- res.writeHead(200);
- res.end('Your first application in Node.js!');
- });
- server.listen(8080);
You can also use same example in two way and the function to be run is the callback function.
We can first save it in a variable and pass this variable to createServer() method.
- var callback_var = function(req, res) {
- res.writeHead(200);
- res.end('Your first application in Node.js!');
- }
- var server = http.createServer(callback_var);
Create a file called main.js and put code into file and save it.
Now open your command prompt and execute the main.js to launch the server :
node main.js
Now open http://127.0.0.1:8080/ in any browser and see response :
In PHP, you get the HTML of website by following way :
- $response_data = file_get_contents("http://example.com");
- print_r($response_data);
In Node.js, you get the HTML of website by following way :
- var http = require('http');
- http.request({ hostname: 'example.com' }, function(res) {
- res.setEncoding('utf8');
- res.on('data', function(d) {
- console.log(d);
- });
- }).end();