First application on Node.js

Let’s write the first simple application for NodeJS. Almost all standard JavaScript language constructs can be used to create applications. The exception is working with the DOM, since the application will run on the server, not in the browser, so the DOM and objects such as window or document in this case will not be available to us.

To do this, we first create a directory on the hard drive for the application. For example, I created a directory C:\node\nodeapp . Let’s create an app.js file in this directory .

Let’s define the following code in the app.js file:

const http = require("http");
response.end("Hello NodeJS!");
}).listen(3000, "",function(){
console.log("Server started listening for requests on port 3000");

Let’s briefly analyze this code.

On the first line, we get the http module, which is needed to create the server. This is a built-in module, and to load it you need to apply the function require():

const http = require("http");

Next, using the method createServer(), a new server is created to listen for incoming connections and process requests. As a parameter, this method takes a function that has two parameters. The first parameter, request, stores all information about the request, and the second parameter, response, is used to send the response. In this case, the response is a simple string “Hello NodeJS!” and sent using the response.end().

But the method http.createServer()only creates a server. In order for the server to start listening for incoming connections, you need to call the method on it listen:

.listen(3000, "",function(){
console.log("Server started listening for requests on port 3000");

This method takes three parameters. The first parameter specifies the local port on which the server is started. The second parameter points to the local address. That is, in this case, the server will start at or localhost on port 3000.

The third parameter represents a function that is run when it starts listening for connections. Here, this function simply prints a diagnostic message to the console.

Now let’s start the server. To do this, open a terminal (in OS X or Linux) or a command prompt (in Windows). Using the cd command , change to the application directory:

cd C:\nodeapp

Then we will call the following command:

node app.js

She starts the server:

Next, open the browser and enter the address http://localhost:3000/ into the address bar :

And we will see the message that was sent in the response.end().