Hello Friends, In my previous article I walked you through the basics of NodeJS and its introductions. And we have written our first “Hello World” program. But believe me that is not going to help if we want to have a good understanding of the NodeJS. Basically NodeJS is server side language and we need to know how to write code which can interact with the server. In this article I will create my first NodeJS server on Ubuntu and Windows.
The code and steps will remain same for both of the operating systems.I will create the server on Ubuntu as I am quite excited about learning Ubuntu and its workings.
This is the Second article in the series for NodeJS free article on this blog:
- Writing my first Hello World program in Node JS
- Simple Trick to create a NodeJS Server on Windows/Ubuntu
- Parsing the Query String, HTTP Method, request Path and payload for NodeJS
NodeJS Server on Ubuntu
-
-
- Create a new file in Ubutu using the command “Nano Server.js” as shown in the below screen shot.
- Once you are in the editor type the below code to create the server.
//Get the dependency var http =require('http'); //The server will send back the response var server = http.createServer(function(req, res){ res.end('Hello World'); }) //Start the server and have it listen on port 3000 server.listen(3000,function(){ console.log("The server is listening on port 3000"); });
- After saving the file by using ‘Ctrl + X’ and hitting enter. Run the Server.js file with Node using the command Node Server.js as shown in the below file.
- Once you are done with executing the file. Go to web browser and browse to “http://localhost:3000”. You can see the output “Hello World”.
-
Code Explanation
At the beginning of the code file you can see the require keyword. It helps to import the contents of one file to another file. NodeJS already provide us the module named ‘http’ which helps us to create socket and other subtleness to creating a server.
Here is more practical example of using require keyword.
This grabs the contents of one file and assigns it to a variable
Module.exports = whatever; This makes the current file “export” something to any other file who “requires” this one as shown in below code.
//FileB.js //Require fileA.js Var myImportedFucntions = require(‘FileA’); //use the foo function from FileA myImportedFunctions.foo();
//FileA.js //creates a lib object Var lib = {}; //Add a foo function to the lib Lib.foo = function ()(console.log(‘hello’)) //exports the whole lib Module.exports = lib;
Once you got the http module in your JavaScript file. Call the createServer method and pass a method as parameter which takes two arguments. These are the request and response object passed to the server.
Since it is a simple serve we return the response with string
Finally starting the server and listening on port 3000.
Please note that all the steps mentioned are same on Windows platform.
Leave a Reply