Table of Contents
If you are using Node.js and creating routes for the first time, you might have seen the following error:
Cannot find module 'express'
.
Replicating the issue
First, let's replicate the issue.
Create a folder called node-cannot-find-module-express
and run the following command inside it.
1npm init -y
This will initialize a default npm project.
Now create a file called index.js
inside the project with the following code:
1const express = require("express")2const app = express()34app.get("/", (req, res) => {5 res.send("hello world")6})78app.listen(8081, function (err) {9 if (err) console.log(err)10 console.log("Server listening on PORT", 8081)11})
Now if you run the command node index.js
, you will receive the following error:
This error occurs because we have imported express in index.js and haven't installed it.
The fix
We can install express
using the following command:
1npm i express
If you wish to use yarn, you can run yarn add express
.
How if you run node index.js
the server should run and you should be able to access the route http://localhost:8081/
If you are getting the error in an existing project, you can try one of the following steps:
- Try running
npm install
oryarn
command. - Delete
node_modules
folder and runnpm install
. - Delete both
node_modules
folder andpackage-lock.json
(yarn.lock
file if you are using yarn) and runnpm install
.
Do follow me on twitter where I post developer insights more often!
Leave a Comment