Node.js with Express.js – Initial Project Setup
- Posted by DT-Tech
- Categories Uncategorized
- Date September 27, 2023
Node.js is a powerful JavaScript runtime that allows you to build server-side applications. Node.js and Express.js are popular tools for building web applications and APIs.
In this step-by-step guide, we’ll walk you through the process of setting up a basic Node.js application with the Express.js framework. By the end of this tutorial, you’ll have a simple Express.js server up and running.
Prerequisites
Initialize the project using the following command npm init -y, using the -y flag i’m just by passing the prompt questions from npm init command and just creating the package.json with the default values.
Install the below list of prerequisites, if you haven’t already
- Node.js: download and install the latest and stable version from the https://nodejs.org. this includes npm(Node Package Manager).
- VSCode: Visual Studio code is a free, popular and widely used source code editor, developed by Microsoft.
Lets setup the project folder
Now run the following command npm init -y, This will create a package.json file, which is used to manage your project’s dependencies and configuration.
Install Express.js
Next step is to install Express.js as a dependency for your project. Run the following command in your terminal npm install express –save
The –save flag will add Express.js as a dependency in your package.json file.
Create an Express Application Server
Create a javascript file app.js in the project folder and the following code to create a basic express application
Now our server is up and running on port 3000, but we haven’t set up any endpoint in our app. lets create a default endpoint for our application. Line number 6 to 8 has the coding for our default get request for our application, which will return “Hello, Express!” response, navigate to http://localhost:3000 in your browser to see the output.
Quick tip
Using node app.js command we can start our server. but, on every change to project file we have to stop and start the node server otherwise it won’t get reflected, to overcome this we can use another npm module nodemon.
Install nodemon as dev dependency
Since we install nodemon as a local package (not as global one), we can’t run nodemon directly from terminal, either we have to provide the fullpath including node_modules folder (or) we can simply add Start script in package.json as given below and run npm start command in the terminal
Now, if we make change in the source code, node mon will take care of restarting the server so we don’t have to restart it manually.
Hope this article helps you to understand the basic setup of node express application, in the next article we will further create our restful api service.