How To Setup A Express.js Project

Express.js is one of the most popular frameworks for building web applications using Node.js. It provides features that make creating a robust and scalable web application easy. This step-by-step guide will go over all the steps for setting up an Express.js project from scratch.

Prerequisites

Installation is pretty straightforward. Before we get started, you will need to have Node.js installed on your system. You can download the latest version of Node.js from the official website. Once installation is complete, you can run the following commands to verify if Node.js and npm are working correctly on your computer.

npm -v
node -v

You're good to go if you see the versions of Node.js and npm in the command line.

Initializing the project

Let's start by creating a new directory for your project and navigate to it:

mkdir my-express-project
cd my-express-project

Next, initialize the Node.js project by running the following command:

npm init -y

This will create a package.json file in your project directory. The package.json file stores metadata about your project, including the dependencies it needs to run. the -y parameter is used to skip the questionnaire altogether. It'll implicitly set yes to all the questions during the npm init command.

Installing Express.js

To install Express.js, run the following command:

npm install express

This will install Express.js and add it as a dependency in your package.json file.

Creating an entry point for the application

Next, we'll create an entry point for your application. This file will be run when you start the application. First, let's create an src directory in the root of our application and then create a file called index.js inside the src folder and add the following code inside that file:

const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
    res.send('Hello Express!');
});
app.listen(port, () => {
    console.log(`App is running on port ${port}`);
});

The above code creates an instance of an Express.js app and sets up a route that listens for GET requests to the app's root path (/). When a request is received, it sends a response with the message "Hello Express!". The application is also set to listen on port 3000.

Adding start script

Next, open your package.json file and add look for scripts section. In this section, add the following script.

"scripts": {
  "start": "node src/index.js"
},

Starting the app

Now from the root of your application, run the following command

npm start

This will start the app, and you should see the message "App is running on port 3000" in the console.

To test the app, open your web browser and navigate to http://localhost:3000. You should see the message "Hello Express!" displayed in the browser.

And That's it! I hope you found this article enjoyable. If you've any queries or feedback, feel free to comment.


Similar Articles