Running Your First “Hello World” Application in Node.js 4 Easy Steps

We assume that on install Node.js In your system

For Check, NPM iNstall run Command-Line and type node -v in cmd  you will see the latest version on your screen

that means NPM is working fine

Now 1st Example code here

Step 1: Initialize Node app – Role of Package.json

Assuming you’ve installed Node.js on your machine, Now create a working directory to hold your application and init the node js app.

Run command npm init, It will create a package.json file for your application in your working directory. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is index.js). For now, just accept the defaults.

Go to Desktop and create a folder named “my-first-node-app” after creating navigate in CMD line to locate this folder

c:/desktop/my-first-node-app/ ..... Like this .

Now Type Command

npm init

Step 2 – Install Express.js

Express.js is the most popular middleware choice when it comes to building web applications with Node.js. It is a web application framework, enables you to build server applications in Node.js

Express JS is a Fast, unopinionated, minimalist web framework for Node.js
expressjs.com

Install Express using the command:

npm install express --save

The –save command tells npm to add the packages as dependencies in the package.json. By default with npm v5.0+, npm install adds the module to the dependencies list in the package.json file. In earlier versions of npm require the –save flag to be specified explicitly.

Now Go to Directory my-first-node-app

creat index.js file and paste the code

//package.json
{
"name": "first-node-app",
"version": "1.0.0",
"description": "my first nodejs express app",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
}
}

Step 3: Write Node.js code

Add the below code to your index.js

const express = require('express');
const app = express();
 
app.get('/', (req, res) => {
  res
    .status(200)
    .send('Hello, world!')
    .end();
});
 
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

Step 4: Run your Node.js application

Let’s start the application locally. Simply start it with the following command:

npm start

If you have not added "start": "node index.js" code to scripts. Still, you can start the application by the following the command:

node index.js //entry point js file

http://localhost:8080/
Congratulations !

 

Was this helpful?

0 / 0

Leave a Reply