Site icon ParallelCodes

Node.js – Building First Application

In the previous post we saw steps for installation of Node.js on Windows machine. In this post we create our first Node.js app. We will first create a very simple Hello Node.js application and then move to creating a web app. Open your Visual Studio code and click on Open folder option. Select a folder where you wish to create your first application. My folder path: D:\nodejs\FirstApp

Click on “Open Folder” option and navigate to your project folder. After navigating to your Node.js project folder click on “Select Folder” option.

Your folder will be opened in Visual studio code. Open a new terminal window by clicking keys

Control + Shift+ ` together.

Your folder path will be shown like below. Type command npm init to create Node.js project inside this folder. You can provide the details like package name, version, description, entry point (index.js will be created by default if not entered anything). I have skipped everything by just pressing “Enter” and using default ones. Once completed, you will be able to see newly created package.json file inside of your folder.

Creating Index.js file:

Create a new js file with name “Index.js” by selecting new file option (shown with arrow in the image below). This file will be the entry point and main file of our app.

Edit Index.js as below: Index.js

console.log('Hello Node.js');
console.log(100 * 7);

Now open the terminal windows by pressing Control + Shift+ ` keys together and type command node index to run the index.js file.

Output:


Now we will create first server-side app using Node.js and Express:

What is Express in Node.js?

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

To install Express, type command npm install express in the terminal window

Now edit the index.js page as below. We will be using port no. 3000 for our app.

index.js:

const express = require('express');
const app = express();
const portNo = 3000;

app.get('/', (req, res) => {
res.send("Hi there. This is a simple Nodejs web page using Express");
});

app.listen(portNo, () => {
console.log('Server started! Visit localhost:' + portNo);
});

Save and on the terminal enter node indexcommand. This will run your app on port no. 3000. Open a browser window and navigate to URL http://localhost:3000/

In the next tutorial of this series we will more about NPM and Node.js modules.


 


Exit mobile version