Create your first NodeJS App

Hello,

After a long break, I’m back to writing with Node.js. I plan to continue my Node.js journey starting from the basics and gradually advancing to the advanced level. Without further ado, let’s dive into the implementation without making the introduction too long.

So, why Node.js?

As you may know, with Node.js, we can develop server-side applications using JavaScript. We can utilize all the features of JavaScript here as well. Its open-source nature, cross-platform compatibility, fast and asynchronous execution, and its use of Google’s V8 engine make it extremely appealing.

How do we create our first project?

First and foremost, we need to have npm (Node Package Manager) installed on our system to develop applications with Node.js. We will use this tool to install all our project dependencies. If npm is not installed on your system, you can install it using the following command for Linux:

sudo apt install npm

Afterward, you can view the versions of npm and Node you have installed by running the following commands:

npm -v
node -v

We have installed npm. Now, let’s create our first Node.js project by creating a folder and running the following command within the folder:

mkdir myapp
cd myapp
npm init

After this process, you will have a “myapp” folder and a “package.json” file within it, which will manage our dependencies. If you have accepted all the default values without making any changes, you can now create the “index.js” file that will manage our application and grant it write permission using the following commands:

touch index.js
sudo chmod 777 index.js

We will also install the Express.js framework for our first Node.js project. But before that, let’s modify our “index.js” file to make it work as follows:

const express = require("express");
var app = express();
app.get("/", function(request, response) {
response.send("Hello World!");
});
app.listen(10000, function() {
console.log("Started application on port %d", 10000);
});

If you try to run the project as it is, you will get an error because Express.js is not installed. So let’s install Express.js:

npm install --save express

After running this command, you can observe the changes related to Express.js in the “package.json” file. Now, let’s run our first Node.js project with the following command:

node index.js

If you see the following message in the console, it means your project is up and running:

Started application on port 10000

Congratulations! You have successfully set up your first Node.js project. Now, open your browser and enter the following information in the address bar to observe that your project is running:

http://localhost:10000/

You will see the message “Hello World!” in your browser. Happy coding!