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 installoryarncommand. - Delete
node_modulesfolder and runnpm install. - Delete both
node_modulesfolder andpackage-lock.json(yarn.lockfile if you are using yarn) and runnpm install.
If you have liked article, do follow me on twitter to get more real time updates!
