Skip to content
node

How to fix: cannot find module 'express' in Node.js

Jul 3, 2022Abhishek EH2 Min Read
How to fix: cannot find module 'express' in Node.js

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:

index.js
1const express = require("express")
2const app = express()
3
4app.get("/", (req, res) => {
5 res.send("hello world")
6})
7
8app.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:

error: Cannot find module express

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 or yarn command.
  • Delete node_modules folder and run npm install.
  • Delete both node_modules folder and package-lock.json (yarn.lock file if you are using yarn) and run npm install.

Do follow me on twitter where I post developer insights more often!

Leave a Comment

© 2024 CodingDeft.Com