Node.js
Creating Hello World Application in Node.js
Details: Node.js
If you are a web developer and have never heard of Node.js, then you should know that Node.js is a platform for building fast and scalable network applications. Node.js uses JavaScript as its main programming language, and it is developed and maintained by the Node.js Foundation. Building an application in Node.js is quite easy; all you need to do is write JavaScript code and upload it to the server.
Running your first Hello World application in Node.js
When you have Node.js installed on your PC, let’s try to display “Hello World” in a browser.
Create file Node.js with file name firstprogram.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
Code Explanation: Node.js
- The simple function is that its the application reads a Javascript file, executes it, and proceeds to return an object. By making use of the object, you can use various functionalities available in the module requested by the required function. Since we want to use the HTTP functionality, we are using the required command (http).
- On the second line, we create a server application that is based on a simple function. Whenever a request is made to the server application, this function is called.
- Once the request is received, this is asking our function to return “Hello World” as a response to the client. The writeHead function is used to send header data, while the end function is used to close the connection to the client.
- Using the server to listen to function; make the server application listen to client requests on port 8080, here you can specify any available port.
Execute code: Node.js
- Save the file on your PC: C:\Users\Your Name\ firstprogram.js
- Navigate to the folder where the file is saved using the command prompt. Enter the command “node firstprogram.js”.
- Your computer now works as a server! If someone tries to access your computer on port 8080, they will get a “Hello World!” message in return!
- Turn on your web browser, and type in the address: http://localhost:8080
Output
Summary
- A simple Node.js application consists of creating a server that listens on a particular port. When a request comes to the server, the server automatically sends a ‘Hello World’ response to the client.