Error cannot find module require dir

I installed npm, bower and gulp. But while running gulp app:serve, I am getting the following error. Please help me. This is the command I run: sachin@sachin:~/Desktop/workspace/myproj/angular/ex (

I installed npm, bower and gulp. But while running gulp app:serve, I am getting the following error.
Please help me.
This is the command I run:
sachin@sachin:~/Desktop/workspace/myproj/angular/ex (master)$gulp app:serve

Result I got:

Error: Cannot find module 'require-dir'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/sachin/Desktop/workspace/myproj/angular/ex/gulpfile.js:14:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

asked Dec 17, 2015 at 7:06

sachin god's user avatar

6

Error: Cannot find module ‘require-dir’

You’ve installed gulp but have not installed its tasks’ dependencies. E.g. if a gulp task has any require('') calls, then it depends on require-dir. Those dependencies are probably in your project’s package.json file. To install all the dependencies run:

npm install 

answered Apr 22, 2016 at 0:55

Shaun Luttin's user avatar

Shaun LuttinShaun Luttin

128k75 gold badges388 silver badges457 bronze badges

0

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

leanne1 opened this issue

Sep 6, 2015

· 4 comments


Closed

Error: Cannot find module ‘require‐dir’

#19

leanne1 opened this issue

Sep 6, 2015

· 4 comments

Comments

@leanne1

I know this has been raised before but i don’t see the solution.

npm install require-dir --save-dev

Package gets installed.

In gulpfile:

var requireDir = require('require‐dir');
requireDir('./folder-a/folder-b');

Error message:

module.js:338
    throw err;
    ^
Error: Cannot find module 'require‐dir'
etc ...

Node v0.12.7

Could you please explain why I am getting this error and if there is a simple fix?

Thanks

@aseemk

This is a good q. We recently upgraded to Node 0.12 and I’ve started seeing this too!

I don’t know what’s causing this yet — I’ve already tried to rework the code to see if I can overcome it, unsuccessfully — but one workaround for now is to npm uninstall require-dir and then undo that.

Sorry about that! I hope to figure out the issue sometime…

@lee-40square

Well, with Node 4.0 I wonder how this issue will work out. At least we’re going to get some stable release cycles. :-)

@Ross-Rawlins

@yocontra

Shouldn’t be an issue anymore, closing.

обновил ноду и галп отказался работать
вот такой конфиг галпа

'use strict';
var requireDir = require('require-dir');
requireDir('./gulp/tasks', {recurse: true});

если сделать классическое

var gulp = require('gulp');
gulp.task('default', function() {
  // place code for your default task here
});

то галп запускается, но у меня развесистая структура тасков с использованием run-sequence для последовательного выполнения. есть гора конфигов с тасками.

если попытаться вебштормом прочитать конфиг галпа то выплёвывает вот это

Failed to list gulp tasks in fitness/gulpfile.js: process finished with exit code 1 (a non-zero exit code means an error)
 * Edit settings

$ /usr/local/bin/node /usr/local/lib/node_modules/gulp/bin/gulp.js --no-color --gulpfile /Users/ass/projects/fitness/gulpfile.js --tasks
module.js:338
    throw err;
    ^

Error: Cannot find module 'gulp-util'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:286:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/ass/projects/fitness/gulpfile.js:2:13)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)

Process finished with exit code 1

если пытаться запустить просто галп из консоли то вот так

$ gulp
Segmentation fault: 11

Вобщем писать всё это богатство в один файл равносильно подписаться на километровую простыню. Вобщем без этой штуки сборка будет совсем грустной.
удалось уже кому-нибудь победить это явление?

в другом проекте где ещё не пытался пофиксить проблему пишет вот так

Failed to list gulp tasks in ng-autokeys/gulpfile.js: process finished with exit code 1 (a non-zero exit code means an error)
 * Edit settings

$ /usr/local/bin/node /usr/local/lib/node_modules/gulp/bin/gulp.js --no-color --gulpfile /Users/ass/projects/ng-autokeys/gulpfile.js --tasks
/Users/ass/projects/ng-autokeys/node_modules/gulp-sass/node_modules/node-sass/lib/extensions.js:148
    throw new Error(['`libsass` bindings not found in ', binaryPath, '. Try reinstalling `node-sass`?'].join(''));
    ^

Error: `libsass` bindings not found in /Users/ass/projects/ng-autokeys/node_modules/gulp-sass/node_modules/node-sass/vendor/darwin-x64-46/binding.node. Try reinstalling `node-sass`?
    at Object.sass.getBinaryPath (/Users/ass/projects/ng-autokeys/node_modules/gulp-sass/node_modules/node-sass/lib/extensions.js:148:11)
    at Object.<anonymous> (/Users/ass/projects/ng-autokeys/node_modules/gulp-sass/node_modules/node-sass/lib/index.js:16:36)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/ass/projects/ng-autokeys/node_modules/gulp-sass/index.js:163:21)
    at Module._compile (module.js:434:26)

Process finished with exit code 1

Я установил npm, bower и gulp. Но во время работы gulp app: serve, я получаю следующую ошибку.
Пожалуйста, помогите мне.
Это команда, которую я запускаю:
sachin @sachin: ~/Desktop/workspace/myproj/ angular/ex (master) $gulp app: serve

Результат, который я получил:

Error: Cannot find module 'require-dir'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/sachin/Desktop/workspace/myproj/angular/ex/gulpfile.js:14:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

17 дек. 2015, в 08:19

Поделиться

Источник

1 ответ

Ошибка: не удается найти модуль ‘require-dir’

Вы установили gulp, но не установили зависимости своих задач. Например. если задача gulp имеет любые вызовы require(''), то это зависит от require-dir. Эти зависимости, вероятно, находятся в файле project.json проекта. Чтобы установить все запущенные зависимости:

npm install 

Shaun Luttin
21 апр. 2016, в 23:30

Поделиться

Ещё вопросы

  • 1Как получить доступ к другой вкладке в Chrome в JavaScript?
  • 1Одиночная JSP с другим классом действия
  • 0Curl возвращает все нормально, когда плохой ip передан CURLOPT_DNS_SERVERS
  • 0DOM-элемент AngularJs внутри of-repeat
  • 1с помощью Android Builder жестов я могу сохранить в каталог данных
  • 0Назначение фонового изображения на панель инструментов ExtJs
  • 1Неисправное приложение <имя_приложения>, версия <номер версии>, неисправный модуль kernel32.dll
  • 0Напишите этот HTML из этого результата JSON (разбор JSON)
  • 0Изменение позиции QGraphicsItems в обработчике событий сцены?
  • 1Как обеспечить переопределение хотя бы одного из двух методов в классе Java?
  • 0несколько целей сборки в надстройке
  • 1Запланированная работа в многоузловой среде
  • 0Сохранение содержимого «фиксированным» под слайд-шоу изображений разных размеров
  • 0Сидите div рядом друг с другом, которые генерируют свою ширину, чтобы заполнить родительский div
  • 1Объединить элементы ListA с частично совпадающими элементами ListB
  • 1Как я могу создать равномерно расположенные кнопки?
  • 0«Папка папки» в htaccess
  • 0boost :: multi_index_container — равные значения
  • 0Изменить имя базы данных таблицы в рабочей среде EER Diagram
  • 0Один тест Угловой контроллер Карма-Жасмин работает, но не другой
  • 1Функция сцепления не работает, когда внутри другой функции
  • 0Javascript; Отслеживание onClick для стороннего приложения, которое позволяет только базовое редактирование HTML-кода
  • 1Как разобрать XML (Fogbugz XML API)?
  • 0как реорганизовать / переименовать макросы в Eclipse C ++
  • 1Последовательность вызовов методов при создании пользовательских компонентов
  • 1добавить краски объектов Android
  • 1Android ViewFlipper showПредыдущий через 300 мс
  • 0Изменение формата даты Jquery Datepicker в Великобритании и форма не отправляется
  • 0Отправить HTML-форму данных в файл с помощью Jquery?
  • 1как получить экземпляр запущенной активности
  • 1импорт android.content.pm.packageParser не может быть разрешен
  • 1Как я могу предотвратить смещение мяча с края экрана? простой пример KeyListenerDemo
  • 0Можно ли изменить частную переменную-член в переопределенном методе?
  • 1KeyboardView.OnKeyboardActionListener
  • 1В последнем запущенном AppInventor необходимо ли подключать телефон к ПК для сборки приложения?
  • 1JAR-файл со всеми библиотеками зависимостей распакован
  • 1Как использовать Python и OpenCV для достижения определения кромки скважины, чтобы откалибровать некоторые мелочи
  • 0Синтаксическая ошибка MySQL 1064 с объединением запросов в MS Access
  • 0Компонент построителя списка тегов Jquery
  • 0AngularJS: навигация по передаваемым параметрам GET в URL
  • 0JQuery UI виджет — как вызвать переопределенный обработчик событий
  • 0Компилятор Clang ++ — аналог для Python
  • 0C # Как подключить и отключить базу данных MySQL
  • 1Непонятная разница в производительности между процессорами Intel
  • 0Есть ли способ получить массив индексируется по именам таблиц в PHP MySQL PDO
  • 1Добавить соединение с помощью учетной записи Google / Facebook в приложение JavaEE
  • 1Значение элемента отличается от того, что добавлено в список
  • 1Несоответствие границ: тип Foo не является допустимой заменой
  • 1Выборочные тесты пружинных блоков данных выборочно проходят
  • 0Получить только имя страницы с .htaccess

Сообщество Overcoder

Я установил npm, bower и gulp. Но при запуске приложения gulp: serve я получаю следующую ошибку.
Пожалуйста, помогите мне.
Это команда, которую я выполняю.:
sachin@sachin:~ / рабочий стол / рабочее пространство/myproj / угловой / ex (master)$gulp app: служить

результат я получил:

Error: Cannot find module 'require-dir'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/sachin/Desktop/workspace/myproj/angular/ex/gulpfile.js:14:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

1 ответов


ошибка: не удается найти модуль «require-dir»

вы установили gulp, но не установили зависимости его задач. Е. Г. если задача глоток имеет какие-либо require('') звонит, то это зависит от require-dir. Эти зависимости, вероятно, находятся в пакете вашего проекта.файл json. Для установки всех зависимостей запустите:

npm install 

JavaScript’s Node.js server supports module export and import in both ECMAScript modules and CommonJS format.

Sometimes, npm will throw an error saying Cannot find module because of module import as shown below:

$ node index.js
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'axios'
Require stack:
- /n-app/index.js
    at ... {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/n-app/index.js' ]
}

Here’s the content of the index.js file:

var axios = require("axios");

The cannot find module error occurs because npm cannot find the module required by the index.js file. In this case, the axios module.

To resolve the error, you need to make sure that axios is installed in the node_modules/ folder.

Please note that the node_modules/ folder must be located in the same directory as the index.js file:

.
├── index.js
├── node_modules
├── package-lock.json
└── package.json

If you have run the npm install command before, then it’s possible that the installation of the module is incomplete or corrupted.

Delete the node_modules/ folder using the rm -rf node_modules command, then run npm install again. That may fix the issue.

Finally, the same error can happen when you require() a local .js file that can’t be found.

Suppose you have a file named lib.js placed in the same folder as the index.js file:

.
├── index.js
└── lib.js

To import the file, you need to specify the correct path in the require() function.

The following code:

var helper = require("lib.js");

Will produce the same error:

$ node index.js
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'lib.js'
Require stack:
- /n-app/index.js
    at ... {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/n-app/index.js' ]
}

This is because the require() function will always look inside the node_modules/ folder.

To let Node.js knows that you are importing a local file, use the absolute path as follows:

The ./ syntax means the root directory where you run the node command. In this case, the folder where index.js is located.

If you have a file one level down like this:

.
├── index.js
└── helpers
    └── lib.js

Then you need to adjust the require() path as shown below:

var helper = require("./helpers/lib.js");

The same also applies when you use the ES modules format as follows:

import helper from "./helpers/lib.mjs";

To conclude, the error “Cannot find module” happens when Node.js can’t find the module that a file is trying to import.

You can see the file and the module that’s causing the issue from the error output generated by Node itself.

And that’s how you resolve the npm cannot find module issue. Great work! 😉

Error: cannot find module [Node npm Error Solved]

If you’re a developer that works with Node JS and JavaScript libraries and frameworks like React, Vue, and Angular, then you might have encountered the «Error: cannot find module» error.

In this article, I’m going to show you how to fix the error.

Why the «Error: cannot find module» Occurs

This error occurs because of the following reasons:

  • you’re trying to import an item from a module you don’t have installed in your project directory
  • you’re importing some things from an outdated package
  • you’re pointing to a file that does not exist

In the screenshot below, you can see that I’m getting the error:

ss1

I’m getting the error because I’m trying to import the freeCodeCamp icon from the react-icons package, which I don’t have installed.

import { FaFreeCodeCamp } from "react-icons/fa";

How to Fix the «cannot find module» Error

If you get this error, the solution is always in the error. The module (package) not found is always specified in the format «Module not found: Error: Can’t resolve ‘package name’ in ‘project directory».

In my case, I got it like this «Module not found: Error: Can’t resolve ‘react-icons/fa’ in ‘C:UsersuserDesktopProjectsAddress Locatoraddress-locatorsrc'».

To fix the error, you need to install the package that is absent in your project directory – npm install package-name or yarn add package-name.

In my case, I need to install the react-icons package so the freeCodeCamp icon can be resolved. I’ll do that by running yarn add react-icons.

Once I install the package and run the app, everything should successfully compile:

ss2

If you install the package but you still get the error, then follow the steps below:

  • delete the node modules folder by running rm -rf node_modules
  • delete package.lock.json file by running rm -f package-lock.json
  • clean up the NPM cache by running npm cache clean --force
  • install all packages again by running npm install

That should fix the error for you.

Conclusion

When you get the “cannot find module” error, or “module not found”, it means you’ve not installed the package you’re trying to use.

If the error occurs even if you have the package installed, then the fixes suggested in this article can help you out.

Thank you for reading.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

“Error: cannot find module” occurs when you try to load a non-existant module in Node – Either via ESM (ECMAScript Modules) or CommonJS module systems.

The error usually looks like this in the console:

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module '/var/www/scripts/app.js'

Enter fullscreen mode

Exit fullscreen mode

Why does «Error: cannot find module» occur?

The error «cannot find module» might happen if you’re trying to:

  • Import a third-party package you haven’t installed yet (with npm or yarn).
  • Import a local module, but the path is wrong.
  • Run a node script in the terminal, but the script doesn’t exist (or path is wrong).
  • Use node standard libraries with TypeScript, but you haven’t installed the @types/node package.
  • The module’s package.json has a main field pointing to an entry file that doesn’t exist.

Before anything, let’s review what a module is and how module systems work in a high level (Or jump to the solutions).

The module system: Modules are the building blocks of an application. Node implements ESM and CommonJS (the default one) module systems to let you organize your code as reusable components.

With modules, you can only expose the public interface of your components and keep the internal functionalities private. This is done by using a module.exports (CommonJS modules) or export (ES Modules).

The following code is an example of a module, which has a function to determine whether a number is odd or not:

// math.js

function isOdd(number) {
return number % 2 !== 0
}

// Make isOdd available to other scripts (and other modules)
module.exports = isOdd

Enter fullscreen mode

Exit fullscreen mode

And here’s how we import it into another script called index.js:

// index.js 
const add = require('./isodd.js') 

console.log(isOdd(3)) 
// output: true

Enter fullscreen mode

Exit fullscreen mode

All the modules you use have an ESM or CommonJS export declaration.

How do module systems find modules?

If the identifier passed to require() or import() is a reference to a file (it starts with /, ../, ./, etc.) in your filesystem, Node will load it from the respective path. Otherwise, it looks it up in the installed modules — inside the node_modules directory.

If the module isn’t found, it raises the «Cannot find module» error.

How to fix the «Cannot find module» error in Node.js?

There are several scenarios this error can happen; Let’s explore each.

Third-party packages: If you try to import a third-party module and get this error (and you’re sure the spelling is correct), you probably haven’t installed the package yet.

Imagine this is the code:

//index.js

const axios = require('axios');

// Make an HTTP request with Axios

Enter fullscreen mode

Exit fullscreen mode

If I run this on my machine, I’ll get the «Cannot find module» error.

And that’s because I haven’t installed it yet. So in my project directory (where my package.json resides), I’d have to install axios package with npm or yarn like so:

npm install axios

Enter fullscreen mode

Exit fullscreen mode

Local modules: Imagine you have a set of utility functions kept in a JavaScript file named utils.js. You want to import a function called getUrl() from this utils.js into your script:

// index.js

const { getUrl } = require('utils')

// Do something here ...

Enter fullscreen mode

Exit fullscreen mode

But when you run npm run build, the build fails:

ERROR in ./app/index.js 30:0-30
Module not found: Error: Can't resolve 'utils' in '/var/www/app'

Enter fullscreen mode

Exit fullscreen mode

In this case, since utils isn’t a reference to a local file, my bundler (Webpack) assumes it’s inside a node_modules directory. The build fails as the utils module isn’t an installed package.

So what I need to do here is to make it an absolute path by adding ./ to my identifier:

// index.js

const { getUrl } = require('./utils.js')

// Do something here ...

Enter fullscreen mode

Exit fullscreen mode

Problem solved.

Sometimes the error occurs because the letter casing is off. File names on Mac and Windows are case-insensitive by default; This means ./Utils and ./utils both work on Mac and Windows (where you develop the app). However, it’ll break on a Linux file system where filenames are case-sensitive.

Running a node script: Another scenario reported by developers is when you run a script with the node command. However, the respective file can’t be located — probably owing to a typo in the name or path.

So always double-check that the path is correct and the script exists. You can always take advantage of the terminal’s autocomplete feature by typing the initial letters and pressing the tab to let it complete the path for you.

node ./scriptName.js

Enter fullscreen mode

Exit fullscreen mode

Node and TypeScript: If you’re coding in TypeScript and you’re importing a built-in Node module like fs, you might get a «Cannot find module ‘fs'» error too.

You can fix the issue by installing @types/node:

npm install @types/node --save-dev

Enter fullscreen mode

Exit fullscreen mode

Even though all packages in node_modules/@types (of any enclosing folder) are included in your compilation. However, it’s worth ensuring node is added under compileOptions.types:

tsconfig.json

{
  compilerOptions: {
    types: [node, jest, express]
  }
}

Enter fullscreen mode

Exit fullscreen mode

Missing entry file in package.json: Each module has an entry file named index.js(by default) unless it’s changed in the module’s package.json via the main field.

{
  name: utils
}

Enter fullscreen mode

Exit fullscreen mode

If you decide to change the main field to another entry file (e.g., main.js), you must ensure the file exists. Or if you rename or relocate that file in the future, remember to update the package.json too.

Missing entry file in package.json has been reported by several users on Stackoverflow.

Importing a module from the global node_modules or a separate directory: Sometimes you might have to use a globally-installed package in your development environment.

If you try to load a globally-installed module in your project, you might get the «Cannot find module» error.

A workaround to this problem is using the npm link command. If the package is installed globally, all you need to do is run the following command while in your project directory:

npm link package-name

As a result, npm will create a symbolic link from the globally installed package name to the node_modules directory of your project — as if you’ve installed it with npm install package-name.

If the module you want to use is a local file residing somewhere in your file system other than the global node_modules (e.g., a module you’re developing), you’ll have to do it in a two-step process:

First step: In the terminal, you need to change the directory to where the module resides and run the npm link (without any parameter). As a result, a symlink is created in the global node_modules that links to your local package.

npm link

Enter fullscreen mode

Exit fullscreen mode

Second step: After that, you change the directory to your project directory (where you want to import the module) and run the following command:

npm link package-name

Enter fullscreen mode

Exit fullscreen mode

This will create a symbolic link from the globally installed package name to the node_modules directory of your project.

Now, you can use the package as if it’s an installed third-party package.

What if the problem persists?

If none of the above solutions worked for you, maybe you’re dealing with corrupted or incomplete installations. In that case, you can take the following steps:

Delete node_module directory:

rm -rf node_modules

Enter fullscreen mode

Exit fullscreen mode

Delete package-lock.json:

rm -f package-lock.json

Enter fullscreen mode

Exit fullscreen mode

Clear the npm cache:

npm cache clean --force

Enter fullscreen mode

Exit fullscreen mode

Install the packages again:

npm install

Enter fullscreen mode

Exit fullscreen mode

This will make a clean install of all the dependencies listed in your package.json file.

I hope these solutions help you fix your code.

Thanks for reading.


❤️ You might like:

  • TypeError: map is not a function in JavaScript in JavaScript (Fixed)
  • Add commas to numbers in JavaScript (Explained with examples)
  • SyntaxError: Unexpected end of JSON input in JavaScript (Fixed)
  • How to fix «ReferenceError: document is not defined» in JavaScript
  • Label htmlFor Property Explained

Понравилась статья? Поделить с друзьями:
  • Error cannot find module react dev utils getpublicurlorpath
  • Error cannot find module puppeteer
  • Error cannot find module pug
  • Error cannot find module npm cli js
  • Error cannot find module node path