I hope you've installed Node.JS on your machine. If you haven't installed then I recommend installing it on your machine. You can visit install npm and Node.JS for help.
Now let's begin our Project
We will use npm to create our first node project, First, let’s create our project directory, then we run the init command
mkdir myfirstproject
cd myfirstproject
npm init -y
After doing these steps. Your directory should look something like this
|_myfirstproject
|__package.json
The "package.json" file may consist of all the project settings and other npm package dependencies. If you open that file it should look like this
{"name": "myfirstproject","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "","license": "ISC"}
The "name" element is the name of your project and if you upload any package to the npm registry it will be under the string that you set as the value of this element, in our case, it's "myfirstproject".
The "main" element specifies the file that acts as your entry point when you run your project. As you can see, we don't have the "index.js" file in our project directory. So, now let's create that index.js file in our project directory by the following command or you can create it like you create other files
touch index.js
In order to create our first Node.JS App, we'll use the express package. In Node.JS, express is your most trustworthy dependency. Express is a minimal and flexible Node.JS web application framework that provides a robust set of features for every application.
To install "Express" dependency we've to follow the following command using npm which helps us to install the express dependency in our project:
npm install express --save
or
npm i express --save
In the above command, we've used "--save" option which helps us to store the dependency in our project's package.json file.
After running the above command, your package.json file will now contain the express dependency and now it should look like this
{"name": "myfirstproject","version": "1.0.0","description": "","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "","license": "ISC","dependencies": {"express": "^4.17.1"}}
After installing express dependency. Let's make some changes in our "index.js" file which should look like this
const express = require("express");
const app = express();
app.get("/", function (request,response){
response.send("Hello World!")
});
app.listen(3000, function () {
console.log("Application Started on port 3000...!!");
});
You can run your project by using the "npm start" command or you can also use, "node index.js" command to run this project.
When you call "http://localhost:3000/" in your browser, you will see the "Hello World!" message.
CONGRATULATIONS...!! You've successfully created your first Node.JS project.