Start Simple Node Js Application

Hello friends here I’m going to show you, how to start node js application as beginner.
First of all you make sure before starting node js you better understand core JavaScript syntax and function and prototyping scope and you should know about some libraries which useful in node js etc because if you start without knowing JavaScript basics you can’t work in node js as a proficient. 
Let’s begin the application, before starting the code you make sure you have installed Node js and some editor according your suitability for my suggestion you should install vscode this is very good for node developer.

After that you create one folder in your drive with the project name and then create one file into folder with name app.js and write some message just for testing like

var msg = “hello swcodes”;
console.log(msg);

After writing this code you just run this file on your cmd command with name app.js such as-

node test.js
hello swcodes

After running this command you will get output which you have written in code and if your file running it means your file working.

Next step remove this lines and let’s start to create server in node js and this very first step to start node application or project.                             

There is two ways which you can create node js server If you want start without using express framework you can write server code with using HTTP library.

const http = require(‘http’);
const port = process.env.PORT || 3000;
const server = http.createServer((req, res) => {
   res.statusCode = 200;
   res.setHeader(‘Content-Type’, ‘text/html’);
   res.end(‘<h1>Hello, swcodes</h1>’);
})

server.listen(port, () => {
   console.log(`Server running at port ${port}`);
})

Second way I can create server in node js with using express framework and I love to use this because this is provide less minimal code facility.

const express = require(‘express’);
const app = express();
const port = process.env.PORT || 3000;

app.get(‘/’, function (req, res) {
   res.send(‘Hello swcodes’);
})

app.listen(port, function () {
   console.log(`Application running at http://localhost:${port}`)
})

News Reporter

Leave a Reply

Your email address will not be published. Required fields are marked *

*

code