Solve - Cannot find module 'express' error in Node.js

avatar

Borislav Hadzhiev

Fri Mar 25 20222 min read

banner

Photo by Clay Banks

Solve - Cannot find module 'express' error in Node.js #

To solve the error "Cannot find module 'express'", install the package by running the command npm install express in the root directory of your project. If you don't have a package.json file, create one by running npm init -y.

cannot find module express

The error occurs when we try to import the express package.

index.js
// ⛔️ Cannot find module 'express' // Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'express' // imported from bobbyhadz-js/index.js import express from 'express'; const app = express(); const port = 3445; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); });

Make sure you have express installed, by opening your terminal in your project's root directory (the one that contains your package.json file) and running the following command:

shell
npm install express

If your project doesn't have a package.json file, you have to initialize one in your project's root directory.

shell
# create package.json file (if you don't have one) npm init -y npm install express

Once you have installed express, the error should be resolved.

If the error is not resolved, try to delete your node_modules directory and the package-lock.json file, re-run npm install and restart your IDE if necessary.

Open your terminal in your project's root directory and run the following commands.

shell
# 👇️ delete node_modules and package-lock.json rm -rf node_modules package-lock.json # 👇️ install packages npm install

Make sure to restart your IDE if the error still persists. VSCode often glitches and a reboot solves things sometimes.

If you get any errors when running these commands, try to manually delete the node_modules and package-lock.json files from your project's root directory.

If you get a permissions error, try re-running the command with sudo, e.g. sudo npm install.

Now you should be able to import and use the express package.

index.js
import express from 'express'; const app = express(); const port = 3445; app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Example app listening on port ${port}`); });

If the error still persists, open your package.json file and make sure it contains the express package in the dependencies object.

package.json
{ // .... "dependencies": { "express": "^4.17.3", // .... }, }
Make sure the express package is added to your dependencies object and not to devDependencies.

You can try to manually add the line and re-run npm install.

shell
npm install
Use the search field on my Home Page to filter through my more than 1,000 articles.