How to Start with NodeJs/ExpressJS
if you don’t have prior knowledge of Node JS and want to start with it, this is for you. it will surely make you understand how to write an app with it.
Firstly you need to make sure you have installed node if not first install it. and it mostly recommends that install NPM(Node Package Manager) with NodeJs. it is an open-source library of NodeJs packages.
node -v - Check node version
npm -v - Check NPM version
sudo apt install nodejs - install nodejs
sudo apt install npm - install NPM
let’s do simply print Hello World in terminal, open terminal and type node and then you can print Hello world by typing console.log(“Hello World”)
Let’s create our first local server with NodeJs
Here we will use ExpressJs which is a web application framework of NodeJS.
or you can see here for without using express.
Step 1
Create a directory named firstapplication and open it into the terminal, now type following
npm init
or
npm init -y
it will create package.json with details you filled.
next, install express by using following command.
npm install express
it will add express in dependencies of package.json.
Step 2
Create a file app.js and write the following and save it.
const express = require('express')const app = express()const PORT = 3001app.get('/', (req,res)=>{ res.send("Server started")})app.listen(PORT,() => { console.log(`Server is listening at Port ${PORT}`)})
const express = require('express')
- importing express moduleconst app = express()
— Creates a new express application.
OR
you can directly use express-generator to create the application and skip above two steps
npm install express-generator
Step 3
Now in terminal type following and you will get the message in terminal written in console.log()
node app.js
open browser and type http://localhost:3001/ in search bar and you will get the message in the display window written in res.send.
I hope it helps.
if you have any doubt or query please reach out to me