Express.js - Create Project
In this tutorial we see how to creating a project with Express.js and how to set up a Node.js environment, install Express, organize folder structures, and build your first Express.js application.
Initialize the Project
Create project directory and initialize with the given command
mkdir my-app cd my-app npm init -y
D:>mkdir my-app D:>cd my-app D:\my-app>npm init -y Wrote to D:\my-app\package.json: { "name": "my-app", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
Install Express.js
Install Express.js with the npm command
npm install express
D:\my-app>npm install express added 65 packages, and audited 66 packages in 3s 13 packages are looking for funding run `npm fund` for details found 0 vulnerabilities npm notice npm notice New minor version of npm available! 10.2.3 -> 10.8.3 npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.8.3 npm notice Run npm install -g npm@10.8.3 to update! npm notice
Folder Structure
Create the Server
In your project directory, create a file named index.js.
- node_modules - This folder contains all the dependencies and packages that your project needs. It is automatically created when you run npm install express command.
- index.js - The main file that starts your app.
- package.json - Contains info about your project.
- package-lock.json - It is automatically generated and updated by npm. Specifies the exact versions of every dependency and sub-dependency installed, including non-direct dependencies.
Basic Express.js Example
// Import the express module
const express = require('express');
// Create an instance of an Express application
const app = express();
// Route to handle GET request at the root URL
app.get('/', (req, res) => {
res.send('Welcome to Express.js!');
});
// Define a port number for the server
const PORT = 5000;
// Start the server and listen on the specified port
app.listen(PORT, () => {
console.log(`Server is running on http:// localhost:${PORT}`);
});
Run the Server
Run the server using the command given below.
node index.js
D:\my-app>node index.js Server is running on http://localhost:5000