DEV Community

nermineslimane
nermineslimane

Posted on

Hello world in nodeJS

Download & Install Node.js

To use node.js, we must first download and install the most recent version from the https://nodejs.org/en URL. When we open the URL, it will automatically determine our operating system and display the appropriate download link, as shown below.

Image description

We can test that node.js is installed correctly on our machine by entering node -v at the command prompt. If node.js was successfully installed, it will display the version of node.js on our machine. To do so, open a command prompt and run the command

node -v

.

Image description

Once we made sure node is installed we will use npm to create our first node project,
First, let’s create our project directory, open the folder in vscode and run the command npm init in the terminal as follows

Image description

we can leave everything as default and your directory should look something like this

Image description

The express package will be used to create our first REST resource. Express is your most dependable friend in Node.js. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

To install it type npm install --save express or npm i --save express, where 'i' is short for install

This is what our index.js file should look like.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
res.send('Hello World!');
});

app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

So let me explain the code we just wrote

The first line declares a variable that will hold the express module, which is retrieved from the node modules folder.

In reality, the module is a function. By assigning the function call to a different variable, you have access to a predetermined set of tools that will greatly simplify your life. You may think of the variable app as an object whose methods you're using to create the program.

The listen method establishes a server and listens for connections on port 3000.

For get requests to the root URL (/), it answers with "Hello World!" It will return a 404 Not Found response for all other paths.

Now we just run the app by typing node index.js and there you have it ! use the tools of your choice to test it you can either use postman or simply your web navigator

Using postman type the url 127.0.0.1:3000/ and here's what you'll get

Image description

The response code is 200 OK and the response body is 'hello world!'

Top comments (0)