Error code enotempty

I get the below-mentioned error when trying to do NPM install in my Dockerfile. I do delete node_modules before running NPM install still I end up with this error. npm ERR! node v6.2.0 npm ERR! np...

I get the below-mentioned error when trying to do NPM install in my Dockerfile. I do delete node_modules before running NPM install still I end up with this error.

npm ERR! node v6.2.0
npm ERR! npm  v3.8.9
npm ERR! path /nodejsAction/node_modules/setprototypeof
npm ERR! code ENOTEMPTY
npm ERR! errno -39
npm ERR! syscall rmdir

npm ERR! ENOTEMPTY: directory not empty, rmdir 
'/nodejsAction/node_modules/setprototypeof'

Any idea how I can fix this? It seems to work properly on my local mac but on my Jenkins server the script fails.

Oded BD's user avatar

Oded BD

2,54526 silver badges28 bronze badges

asked May 4, 2017 at 9:23

Sandy's user avatar

1

I think the following command might be more appropriate:

rm -r node_modules

This will remove the node_modules folder in your repository. The command npm install should work now.

If you are using Webpack, you can also remove the dist folder using rm -r dist and re-build your repository.

answered Nov 18, 2021 at 18:54

Sam Rothstein's user avatar

I had the same error/issue, and I removed the directory.

rm -r node_modules/MODULE

It simply worked!

answered Aug 13, 2021 at 13:27

X 47 48 - IR's user avatar

X 47 48 — IRX 47 48 — IR

1,1601 gold badge12 silver badges26 bronze badges

3

I had the same issue, i did following:
1. Restart system
2. Close VS, VSCode or any editor that has JS files open.
3. Apparently, you might have to do npm install in other directories too before doing it in target folder.

answered Apr 21, 2020 at 5:54

Ganesh Jadhav's user avatar

In my case, the ENOTEMPTY followed an ERR_SOCKET_TIMEOUT. It also carried an instruction to rename the module (uuid to uuid-<some string>, nanoid to nanoid-<some string>)- renaming led to the same issue, with or without verifying the cache. The fix for this, without having to nuke the cache, was to delete both the source and destination modules

rm -r node_modules/<module>
rm -r node_modules/.<module>-<string suffix>

and then continue the install. Quite similar to an answer given here but deleting just the module wasn’t enough for me

answered Apr 27, 2022 at 2:35

Tofi A.'s user avatar

Tofi A.Tofi A.

731 silver badge7 bronze badges

0

In my case it was with Reactjs and when I was trying to install react-boostrap.

Solution

You should remove the node_modules directory in your project.
Run:

  1. rm -r node_modules

or with superuser privileges

sudo rm -r node_modules . You need to enter your sudo password for this to work

  1. Run npm i to reinstall your dependencies.

Sometimes you may end up with a type error if you’re working with React, when you run npm audit fix. Type error like this:

*npm ERR! code ERR_INVALID_ARG_TYPE*

If this is your case, you should replace your react-scripts version in package.json file to ^3.4.1 (as this work for me)

Remove the node_modules again and rerun npm i

It should be fine when you run npm audit fix and you can continue installing your dependency

answered Aug 4, 2022 at 16:08

Mayor's user avatar

MayorMayor

213 bronze badges

  1. del node modules folder
  2. del package-lock.json file
  3. npm i
    OR
  4. npm i —save —legacy-peer-deps

answered Jun 16, 2022 at 16:13

Yasir's user avatar

YasirYasir

3993 silver badges10 bronze badges

Error message say that /nodejsAction/node_modules/setprototypeof is not empty

You have to remove this directory or rename this directory in my case I removed this particular directory

This error show that to Install or update NPM Package you have to remove the particular directory

answered Apr 6, 2022 at 12:22

Gulshan Prajapati's user avatar

rm -r node_modules && rm -r dist

answered Jan 31 at 20:58

Yasir's user avatar

YasirYasir

3993 silver badges10 bronze badges

If there’s a rename attempt and it fails, the system throws the error. The rename fails because there’s already a backup package with a .module<uuid> present. You should delete all backup packages. You may need to backup .package-lock.json

mv node_modules/.package-lock.json node_modules/package-lock.json
rm -rf node_modules/.*
mv node_modules/package-lock.json node_modules/.package-lock.json

answered Feb 4 at 9:57

TheMaster's user avatar

TheMasterTheMaster

43.9k6 gold badges55 silver badges79 bronze badges

Содержание

  1. Common errors
  2. AppDataRoamingnpm’ on Windows 7 permalink» >
  3. Распространённые ошибки при использовании npm, которых лучше не совершать
  4. 1. Ручное добавление зависимостей в файл package.json
  5. 2. Ограничение зависимостей типа peerDependencies конкретной версией патча
  6. 3. Публикация нескольких модулей в виде единственного пакета
  7. 4. Случайная публикация секретных данных
  8. 5. Использование обычного токена аутентификации
  9. 6. Бессмысленное обновление пакетов
  10. 7. Удаление файла package-lock.json
  11. Итоги
  12. Common errors
  13. Errors
  14. Сломанная установка npm
  15. Random errors
  16. Не найдена совместимая версия
  17. Permissions errors
  18. Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7″ onmousemove=»i18n(this)»> Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ в Windows 7
  19. No space
  20. No git
  21. Запуск блока Vagrant на Windows не удается из-за проблем с длиной пути
  22. git: and ssh+git: URLs for GitHub repos, breaking proxies» onmousemove=»i18n(this)»>npm использует только git: и ssh+git: URL-адреса для репозиториев GitHub, нарушая прокси
  23. SSL Error
  24. SSL-intercepting proxy
  25. Не найдено/Ошибка сервера
  26. Invalid JSON
  27. ENOENT / ENOTEMPTY errors in output» onmousemove=»i18n(this)»>Многие ошибки ENOENT / ENOTEMPTY в выводе
  28. cb() never called! when using shrinkwrapped dependencies» onmousemove=»i18n(this)»> cb() never called! при использовании термоусадочных зависимостей
  29. npm login errors» onmousemove=»i18n(this)»> npm login ошибки входа в npm
  30. npm hangs on Windows at addRemoteTarball » onmousemove=»i18n(this)»> npm зависает в Windows на addRemoteTarball

Common errors

Broken npm installation

If your npm is broken:

  • On Mac or Linux, reinstall npm.
  • Windows: If you’re on Windows and you have a broken installation, the easiest thing to do is to reinstall node from the official installer (see this note about installing the latest stable version).
  • Some strange issues can be resolved by simply running npm cache clean and trying again.
  • If you are having trouble with npm install , use the -verbose option to see more details.

No compatible version found

AppDataRoamingnpm’ on Windows 7 permalink» >

Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7

The error Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7 is a consequence of joyent/node#8141, and is an issue with the Node installer for Windows. The workaround is to ensure that C:Users AppDataRoamingnpm exists and is writable with your normal user account.

You are trying to install on a drive that either has no space, or has no permission to write.

  • Free some disk space or
  • Set the tmp folder somewhere with more space: npm config set tmp /path/to/big/drive/tmp or
  • Build Node yourself and install it somewhere writable with lots of space.

You need to install git. Or, you may need to add your git information to your npm profile. You can do this from the command line or the website. For more information, see «Managing your profile settings».

Running a Vagrant box on Windows fails due to path length issues

@drmyersii went through what sounds like a lot of painful trial and error to come up with a working solution involving Windows long paths and some custom Vagrant configuration:

In the code above, I am appending \? to the current directory absolute path. This will actually force the Windows API to allow an increase in the MAX_PATH variable (normally capped at 260). Read more about max path. This is happening during the sharedfolder creation which is intentionally handled by VBoxManage and not Vagrant’s «synced_folder» method. The last bit is pretty self-explanatory; we create the new shared folder and then make sure it’s mounted each time the machine is accessed or touched since Vagrant likes to reload its mounts/shared folders on each load.

npm only uses git: and ssh+git: URLs for GitHub repos, breaking proxies

I fixed this issue for several of my colleagues by running the following two commands:

One thing we noticed is that the .gitconfig used is not always the one expected so if you are on a machine that modified the home path to a shared drive, you need to ensure that your .gitconfig is the same on both your shared drive and in c:users[your user]

You are trying to talk SSL to an unencrypted endpoint. More often than not, this is due to a proxy configuration error (see also this helpful, if dated, guide). In this case, you do not want to disable strict-ssl – you may need to set up a CA / CA file for use with your proxy, but it’s much better to take the time to figure that out than disabling SSL protection.

This problem will happen if you’re running Node 0.6. Please upgrade to node 0.8 or above. See this post for details.

You could also try these workarounds: npm config set ca «» or npm config set strict-ssl false

  • upgrade your version of npm npm install npm -g —ca=»»
  • tell your current version of npm to use known registrars npm config set ca=»»

If this does not fix the problem, then you may have an SSL-intercepting proxy. (For example, https://github.com/npm/npm/issues/7439#issuecomment-76024878)

Not found / Server error

  • It’s most likely a temporary npm registry glitch. Check npm server status and try again later.
  • If the error persists, perhaps the published package is corrupt. Contact the package owner and have them publish a new version of the package.
  • Possible temporary npm registry glitch, or corrupted local server cache. Run npm cache clean and/or try again later.
  • This can be caused by corporate proxies that give HTML responses to package.json requests. Check npm’s proxy configuration.
  • Check that it’s not a problem with a package you’re trying to install (e.g. invalid package.json ).

Many ENOENT / ENOTEMPTY errors in output

npm is written to use resources efficiently on install, and part of this is that it tries to do as many things concurrently as is practical. Sometimes this results in race conditions and other synchronization issues. As of npm 2.0.0, a very large number of these issues were addressed. If you see ENOENT lstat , ENOENT chmod , ENOTEMPTY unlink , or something similar in your log output, try updating npm to the latest version. If the problem persists, look at npm/npm#6043 and see if somebody has already discussed your issue.

cb() never called! when using shrinkwrapped dependencies

Take a look at issue #5920. We’re working on fixing this one, but it’s a fairly subtle race condition and it’s taking us a little time. You might try moving your npm-shrinkwrap.json file out of the way until we have this fixed. This has been fixed in versions of npm newer than npm@2.1.5 , so update to npm@latest .

npm login errors

Sometimes npm login fails for no obvious reason. The first thing to do is to log in at https://www.npmjs.com/login and check that your e-mail address on npmjs.com matches the email address you are giving to npm login .

If that’s not the problem, or if you are seeing the message «may not mix password_sha and pbkdf2» , then

  1. Log in at https://npmjs.com/
  2. Change password at https://npmjs.com/password – you can even «change» it to the same password
  3. Clear login-related fields from

/.npmrc – e.g., by running sed -ie ‘/registry.npmjs.org/d’

and it generally seems to work.

npm hangs on Windows at addRemoteTarball

Check if you have two temp directories set in your .npmrc :

Look for lines defining the tmp config variable. If you find more than one, remove all but one of them.

See https://github.com/npm/npm/issues/7590 for more about this unusual problem.

npm not running the latest version on a Windows machine

Источник

Распространённые ошибки при использовании npm, которых лучше не совершать

Npm — это крупнейший менеджер пакетов. Его сравнительно просто и понятно использовать в практике веб-разработки. Но когда речь заходит о применении собственных конфигураций или об использовании продвинутых возможностей npm, многое может пойти не так.

В этом материале я расскажу о семи распространённых ошибках, которые веб-разработчики допускают при работе с npm. В частности, речь пойдёт об управлении зависимостями, о публикации пакетов и ещё о некоторых важных вещах.

1. Ручное добавление зависимостей в файл package.json

Не стоит самостоятельно редактировать файл package.json , так как это может нарушить синхронизацию между этим файлом и package-lock.json .

Вместо этого можно прибегнуть к командам, выполняемым в командной строке, вроде npm i —save и npm i —save-dev , что позволит автоматически обновлять и package.json , и package-lock.json . При таком подходе система ещё и уведомит разработчика о том, что в версиях зависимостей, упомянутых в этих двух файлах, имеются расхождения.

Правда, надо отметить, что использование подобных команд не всегда гарантирует беспроблемное обновление зависимостей.

Например, если выполнить команду вида npm i —save package@

1.0.0 , можно ожидать, что в package.json будет отражена версия пакета, соответствующая той, что указана в команде после @ . Но в подобной команде можно использовать не спецификатор версии

, а спецификатор версии ^ , что позволит расширить возможности по автоматическому обновлению пакета.

Рекомендуется тщательно проверять package.json после обновления зависимостей.

2. Ограничение зависимостей типа peerDependencies конкретной версией патча

Обычно зависимости типа peerDependencies используются для того чтобы обеспечить правильную работу плагинов с хост-пакетами. Если ограничить подобные зависимости конкретными версиями патчей — результат может оказаться не очень хорошим.

Рассмотрим простой пример для того чтобы разобраться с фундаментальной причиной этой проблемы.

В соответствии с вышеприведённым кодом, модуль tea-latte нуждается в конкретной версии (1.x) пакета tea .

Но в проекте могут быть другие пакеты или модули, которые зависят от самой свежей версии пакета tea . В результате ограничение версии пакета tea может привести к непредсказуемому поведению приложения.

Обратите внимание на то, что npm версий 1, 2 и 7 автоматически установит зависимости peerDependencies , если явной зависимости от них нет, выше в дереве зависимостей. А npm версий 3, 4, 5 и 6 выдаст предупреждение.

3. Публикация нескольких модулей в виде единственного пакета

Независимый компонент и схема его зависимостей

Идёт ли речь об UI-библиотеке, о наборе полезных инструментов, или о любой другой группе модулей, публикация нескольких таких сущностей в виде единого пакета — это, практически всегда, неудачная идея.

Нет причин, по которым разработчикам стоит принуждать потребителей их кода привязывать свои проекты к целому набору модулей и компонентов, в ситуациях, когда потребителям все эти модули или компоненты не нужны. У потребителей должна быть возможность выбора конкретного модуля и его версии, он не должен сталкиваться с бессмысленными обновлениями пакетов, происходящими из-за того, что ему не нужно.

Вы, вероятнее всего, согласитесь с вышесказанным, но вас может напугать мысль о необходимости управления монорепозиторием для поддержки всех этих пакетов. На это я могу сказать, что бояться тут нечего.

JavaScript-экосистема уже далеко ушла от тех времён, когда шёл спор между приверженцами монорепозиториев и полирепозиториев.

Теперь мы можем пользоваться возможностями публикации независимых компонентов из простых проектов, наподобие тех, что созданы с использованием Create React App, с возможностью контроля версий, с автоматическим созданием package.json , документации и многого другого. В частности, такие возможности даёт платформа Bit.

4. Случайная публикация секретных данных

Если вы случайно опубликовали модуль, содержащий секретные данные, то первым делом нужно отменить его публикацию.

Но это не решает проблему утечки данных, так как после того, как модуль опубликован, он копируется на все зеркала репозитория пакетов. И если отменить его публикацию — это не позволит исправить ситуацию.

Использование белых списков — это удобный способ, используемый для контроля того, что публикуется в репозиториях пакетов, и для предотвращения публикации секретных данных.

Для применения белых списков публикуемых материалов достаточно добавить в package.json свойство с именем files . В нём можно указать список файлов или папок, которые подлежат публикации.

Рекомендую использовать белые списки для управления тем, что попадает в пакеты, которые планируется публиковать.

5. Использование обычного токена аутентификации

Если вы используете в CI/CD-цепочке приватные модули, вам понадобится воспользоваться токеном аутентификации. Но инструменты npm, работающие в командной строке, при создании подобных токенов не позволяют управлять правами на чтение и на запись.

Токен создаётся вручную, с использованием общедоступного API репозитория, что позволяет избежать уязвимостей систем безопасности, вызванных токенами.

Нижеприведённая команда позволяет создать токен с ограничением доступа только чтением данных:

На сайте npm можно просматривать, добавлять и удалять подобные токены.

Команда для доступа к операциям с токенами

6. Бессмысленное обновление пакетов

Использование самых свежих версий пакетов — это хорошо. Но не стоит обновлять пакеты только из-за того, что выходят их новые версии. Разберёмся с причинами этой рекомендации:

  • В самой свежей версии пакета могут быть ошибки.
  • Обновление пакетов без тщательного изучения изменений может привести к неожиданным эффектам в приложении.
  • Новые возможности могут оказаться ненужными в конкретном проекте.
  • Установка самой свежей версии некоего пакета может привести к проблемам в работе других пакетов, которые от него зависят.

В результате перед обновлением пакетов надо оценить изменения, внесённые в их новые версии, надо подумать о возможных проблемах с совместимостью, а уже после этого, если решено, что это нужно, выполнять обновление.

7. Удаление файла package-lock.json

Веб-разработчики часто удаляют файл package-lock.json для того чтобы решить проблемы, возникающие при работе с npm.

Но так лучше не делать, так как этот файл хранит сведения о точной версии каждого установленного пакета. Если, например, выполнить команду npm update , сведения об обновлённых зависимостях будут отражены в файле package-lock.json .

В результате, вместо того, чтобы, в попытке решения некоей проблемы, удалять файл package-lock.json , можно попробовать следующее:

  • Разрешить конфликты package.json .
  • Изъять package-lock.json из главной ветки репозитория.
  • Снова выполнить команду npm install .

Итоги

Npm — это важнейшая часть любого проекта, основанного на JavaScript, этот менеджер пакетов помогает разработчикам эффективно управлять зависимостями своих проектов.

Но работа с npm сопряжена с множеством ошибок, некоторые из которых могут привести к серьёзным проблемам. Хочется надеяться, что то, о чём мы говорили в этом материале, поможет вам совершать меньше ошибок при работе с npm.

Сталкивались ли вы когда-нибудь с проблемами, вызванными ошибками, допущенными при работе с npm?

Источник

Common errors

Errors

Сломанная установка npm

Если ваш npm сломан:

  • На Mac или Linux переустановите npm .
  • Windows: если вы используете Windows и у вас не работает установка, проще всего переустановить узел из официального установщика (см. Это примечание об установке последней стабильной версии ).

Random errors

  • npm cache clean and trying again.» onmousemove=»i18n(this)»>Некоторые странные проблемы можно решить, просто запустив npm cache clean и повторив попытку.
  • npm install , use the -verbose option to see more details.» onmousemove=»i18n(this)»>Если у вас возникли проблемы с npm install , используйте параметр -verbose , чтобы увидеть более подробную информацию.

Не найдена совместимая версия

Permissions errors

См. Обсуждения в разделах « Загрузка и установка Node.js и npm » и « Устранение ошибок разрешений EACCES при глобальной установке пакетов », чтобы узнать, как избежать и устранить ошибки разрешений.

Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7″ onmousemove=»i18n(this)»> Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ в Windows 7

Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ on Windows 7 is a consequence of joyent/node#8141, and is an issue with the Node installer for Windows. The workaround is to ensure that C:Users AppDataRoamingnpm exists and is writable with your normal user account.» onmousemove=»i18n(this)»>Ошибка Error: ENOENT, stat ‘C:Users AppDataRoamingnpm’ в Windows 7 является следствием joyent / node # 8141 и является проблемой установщика Node для Windows. Обходной путь — убедиться, что C:Users AppDataRoamingnpm существует и доступен для записи с вашей обычной учетной записью.

No space

Вы пытаетесь установить диск,на котором либо нет места,либо нет разрешения на запись.

  • Освободите место на диске или
  • npm config set tmp /path/to/big/drive/tmp or» onmousemove=»i18n(this)»>Установите папку tmp где-нибудь с большим пространством: npm config set tmp /path/to/big/drive/tmp или
  • Соберите Node самостоятельно и установите его где-нибудь,где есть место для записи с большим количеством места.

No git

Вам необходимо установить git . Или вам может потребоваться добавить информацию о git в свой профиль npm. Вы можете сделать это из командной строки или на веб-сайте. Для получения дополнительной информации см. « Управление настройками вашего профиля ».

Запуск блока Vagrant на Windows не удается из-за проблем с длиной пути

@drmyersii прошел через много мучительных проб и ошибок, чтобы предложить рабочее решение, включающее длинные пути Windows и некоторую настраиваемую конфигурацию Vagrant:

\? to the current directory absolute path. This will actually force the Windows API to allow an increase in the MAX_PATH variable (normally capped at 260). Read more about max path. This is happening during the sharedfolder creation which is intentionally handled by VBoxManage and not Vagrant’s «synced_folder» method. The last bit is pretty self-explanatory; we create the new shared folder and then make sure it’s mounted each time the machine is accessed or touched since Vagrant likes to reload its mounts/shared folders on each load.» onmousemove=»i18n(this)»>В приведенном выше коде я добавляю \? К абсолютному пути текущего каталога. Это фактически заставит Windows API разрешить увеличение переменной MAX_PATH (обычно не более 260). Подробнее о максимальном пути . Это происходит во время создания общей папки, которая намеренно обрабатывается VBoxManage, а не методом Vagrant «synced_folder». Последний пункт довольно понятен; мы создаем новую общую папку, а затем убеждаемся, что она монтируется каждый раз, когда к машине обращаются или касаются, поскольку Vagrant любит перезагружать свои монтированные / общие папки при каждой загрузке.

git: and ssh+git: URLs for GitHub repos, breaking proxies» onmousemove=»i18n(this)»>npm использует только git: и ssh+git: URL-адреса для репозиториев GitHub, нарушая прокси

@LaurentGoderre исправил это с помощью некоторых уловок Git :

Я исправил эту проблему для нескольких своих коллег,запустив следующие две команды:

.gitconfig used is not always the one expected so if you are on a machine that modified the home path to a shared drive, you need to ensure that your .gitconfig is the same on both your shared drive and in c:users[your user] » onmousemove=»i18n(this)»>Одна вещь, которую мы заметили, заключается в том, что используемый .gitconfig не всегда является ожидаемым, поэтому, если вы находитесь на машине, которая изменила домашний путь к общему диску, вам необходимо убедиться, что ваш .gitconfig одинаков как на вашем общем диске, так и на в c:users[your user]

SSL Error

strict-ssl – you may need to set up a CA / CA file for use with your proxy, but it’s much better to take the time to figure that out than disabling SSL protection.» onmousemove=»i18n(this)»>Вы пытаетесь подключить SSL к незашифрованной конечной точке. Чаще всего это связано с ошибкой конфигурации прокси (см. также это полезное, хотя и устаревшее, руководство ). В этом случае вам не нужно отключать strict-ssl — вам может понадобиться настроить файл CA/CA для использования с вашим прокси, но гораздо лучше потратить время на то, чтобы разобраться в этом, чем отключать защиту SSL.

Эта проблема может возникнуть, если вы используете Node 0.6. Пожалуйста, обновите до версии 0.8 или выше. Подробности смотрите в этом посте .

npm config set ca «» or npm config set strict-ssl false ‘ onmousemove=»i18n(this)»>Вы также можете попробовать следующие обходные пути: npm config set ca «» или npm config set strict-ssl false

  • npm install npm -g —ca=»» ‘ onmousemove=»i18n(this)»>обновите свою версию npm npm install npm -g —ca=»»
  • npm config set ca=»» ‘ onmousemove=»i18n(this)»>указать вашей текущей версии npm использовать известных регистраторов npm config set ca=»»

Если это не решит проблему, возможно, у вас прокси для перехвата SSL. (Например, https://github.com/npm/npm/issues/7439#issuecomment-76024878 )

SSL-intercepting proxy

Не найдено/Ошибка сервера

  • Скорее всего, это временный сбой реестра npm. Проверьте статус сервера npm и повторите попытку позже.
  • Если ошибка сохраняется,возможно,опубликованный пакет поврежден.Свяжитесь с владельцем пакета и попросите его опубликовать новую версию пакета.

Invalid JSON

  • npm cache clean and/or try again later.» onmousemove=»i18n(this)»>Возможный временный сбой реестра npm или поврежденный кеш локального сервера. Запустите npm cache clean и / или повторите попытку позже.
  • package.json requests. Check npm’s proxy configuration.» onmousemove=»i18n(this)»>Это может быть вызвано корпоративными прокси, которые дают HTML-ответы на запросы package.json . Проверьте конфигурацию прокси-сервера npm .
  • package.json ).» onmousemove=»i18n(this)»>Убедитесь, что это не проблема с пакетом, который вы пытаетесь установить (например, недопустимый package.json ).

ENOENT / ENOTEMPTY errors in output» onmousemove=»i18n(this)»>Многие ошибки ENOENT / ENOTEMPTY в выводе

ENOENT lstat , ENOENT chmod , ENOTEMPTY unlink , or something similar in your log output, try updating npm to the latest version. If the problem persists, look at npm/npm#6043 and see if somebody has already discussed your issue.’ onmousemove=»i18n(this)»>npm написан для эффективного использования ресурсов при установке, и отчасти это связано с тем, что он пытается делать столько вещей одновременно, сколько это возможно. Иногда это приводит к состояниям гонки и другим проблемам синхронизации. Начиная с npm 2.0.0, было решено очень большое количество этих проблем. Если в выводе журнала вы видите ENOENT lstat , ENOENT chmod , ENOTEMPTY unlink или что-то подобное, попробуйте обновить npm до последней версии. Если проблема не исчезнет, ​​посмотрите npm / npm # 6043 и посмотрите, обсуждал ли кто-нибудь вашу проблему.

cb() never called! when using shrinkwrapped dependencies» onmousemove=»i18n(this)»> cb() never called! при использовании термоусадочных зависимостей

We’re working on fixing this one, but it’s a fairly subtle race condition and it’s taking us a little time. You might try moving your npm-shrinkwrap.json file out of the way until we have this fixed. This has been fixed in versions of npm newer than npm@2.1.5 , so update to npm@latest .» onmousemove=»i18n(this)»>Взгляните на выпуск # 5920 . Мы работаем над исправлением этого, но это довольно сложное состояние гонки, и это отнимает у нас немного времени. Вы можете попробовать переместить файл npm-shrinkwrap.json в сторону, пока мы не исправим это. Это было исправлено в версиях npm новее, чем npm@2.1.5 , поэтому обновите до npm@latest .

npm login errors» onmousemove=»i18n(this)»> npm login ошибки входа в npm

npm login fails for no obvious reason. The first thing to do is to log in at https://www.npmjs.com/login and check that your e-mail address on npmjs.com matches the email address you are giving to npm login .’ onmousemove=»i18n(this)»>Иногда npm login завершается неудачно без очевидной причины. Первое, что нужно сделать, это войти в систему на https://www.npmjs.com/login и убедиться, что ваш адрес электронной почты на npmjs.com совпадает с адресом электронной почты, который вы указываете для npm login в npm .

«may not mix password_sha and pbkdf2″ , then» onmousemove=»i18n(this)»>Если проблема не в этом или вы видите сообщение «may not mix password_sha and pbkdf2» , то

  1. Авторизуйтесь на https://npmjs.com/
  2. Смените пароль на https://npmjs.com/password — вы даже можете «сменить» его на тот же пароль

/.npmrc – e.g., by running sed -ie ‘/registry.npmjs.org/d’

/.npmrc » onmousemove=»i18n(this)»>Очистите поля, связанные с входом в систему, из

/.npmrc , например, запустив sed -ie ‘/registry.npmjs.org/d’

и в целом,похоже,это работает.

npm hangs on Windows at addRemoteTarball » onmousemove=»i18n(this)»> npm зависает в Windows на addRemoteTarball

.npmrc :» onmousemove=»i18n(this)»>Проверьте, установлены ли в вашем .npmrc два временных каталога :

tmp config variable. If you find more than one, remove all but one of them.» onmousemove=»i18n(this)»>Найдите строки, определяющие переменную конфигурации tmp . Если вы найдете более одного, удалите все, кроме одного.

Источник

Я столкнулся со следующей ошибкой, когда попытался установить несколько новых пакетов с помощью npm install. Это произошло, когда я сделал npm install a-new-package --save, а затем удалил файл package-lock.json, чтобы все обновить.

npm ERR! code ENOTEMPTY
npm ERR! syscall rename
npm ERR! path /Users/memphismeng/Documents/React Programming/Foot-in-The-Door/mobile/fitd/node_modules/@babel/plugin-proposal-decorators
npm ERR! dest /Users/memphismeng/Documents/React Programming/Foot-in-The-Door/mobile/fitd/node_modules/@babel/.plugin-proposal-decorators-ysLLPQFw
npm ERR! errno -66
npm ERR! ENOTEMPTY: directory not empty, rename '/Users/memphismeng/Documents/React Programming/Foot-in-The-Door/mobile/fitd/node_modules/@babel/plugin-proposal-decorators' -> '/Users/memphismeng/Documents/React Programming/Foot-in-The-Door/mobile/fitd/node_modules/@babel/.plugin-proposal-decorators-ysLLPQFw'

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/memphismeng/.npm/_logs/2021-06-15T18_07_01_162Z-debug.log

Что пошло не так? Я также пробовал npm audit fix --legacy-peer-deps, но это не сработало.

3 ответа

Лучший ответ

Возможно, удаление папки node_modules и файла package-lock.json, а затем повторная установка npm решит вашу проблему.

Итак, рассмотрим следующие команды для применения вышеуказанных операций:

npm remove node_modules 
npm remove package-lock.json
npm install 


20

EdwardM
9 Авг 2022 в 20:38

Очевидно, что удаление package.json работает, но это не всегда желаемое решение. Иногда хочется запустить:

 npm i --package-lock-only //to update package.lock.json
 npm audit fix

А потом:

npm i

И это должна быть первая попытка, но я не знаю, почему это не сработало в моем случае, который находится в собственном сценарии реакции. Похоже, что ошибка «npm install error ENOTEMPTY» происходит, когда npm пытается записать в папку, которая не пуста, и в данном случае в «node_modules/@babel/.plugin-proposal-decorators-ysLLPQFw». Если вы запустите:

rm -rf node_modules/@babel/.plugin-proposal-decorators-ysLLPQFw

А потом:

npm i

На этот раз должно сработать. Это должен быть процесс очистки от react-native, и при работе с веб-стартовым набором, таким как CRA, со мной этого никогда не случалось.


2

Eran Or
21 Окт 2021 в 23:32

У меня была довольно похожая проблема при работе с npm. Что сработало для меня как шарм, так это обновление моих пакетов и зависимостей для проекта, в частности react-scripts.

Проверьте, какие у вас устаревшие пакеты:

npm outdated

Или следуйте фрагментам кода этот парень из среды, который автоматизирует задачу проверки и обновления ваших пакетов один за другим.


0

cigien
26 Фев 2022 в 08:50

Errors

  • Сломанная установка npm
  • Random errors
  • Не найдена совместимая версия
  • Permissions errors
  • Error: ENOENT, stat 'C:Users<user>AppDataRoamingnpm' в Windows 7
  • No space
  • No git
  • Запуск блока Vagrant на Windows не удается из-за проблем с длиной пути
  • npm использует только git: и ssh+git: URL-адреса для репозиториев GitHub, нарушая прокси
  • SSL error
  • SSL-intercepting proxy
  • Не найдено/Ошибка сервера
  • Invalid JSON
  • Многие ошибки ENOENT / ENOTEMPTY в выводе
  • cb() never called! при использовании термоусадочных зависимостей
  • ошибки при входе в npm
  • npm зависает в Windows на addRemoteTarball
  • npm не запускает последнюю версию на машине с Windows

Сломанная установка npm

Если ваш npm сломан:

  • На Mac или Linux переустановите npm .
  • Windows: если вы используете Windows и у вас не работает установка, проще всего переустановить узел из официального установщика (см. Это примечание об установке последней стабильной версии ).

Random errors

  • Некоторые странные проблемы можно решить, просто запустив npm cache clean и повторив попытку.
  • Если у вас возникли проблемы с npm install , используйте параметр -verbose , чтобы увидеть более подробную информацию.

Не найдена совместимая версия

У вас устаревший npm. Пожалуйста, обновите npm до последней стабильной версии .

Permissions errors

См. Обсуждения в разделах « Загрузка и установка Node.js и npm » и « Устранение ошибок разрешений EACCES при глобальной установке пакетов », чтобы узнать, как избежать и устранить ошибки разрешений.

Error: ENOENT, stat 'C:Users<user>AppDataRoamingnpm' в Windows 7

Ошибка Error: ENOENT, stat 'C:Users<user>AppDataRoamingnpm' в Windows 7 является следствием joyent / node # 8141 и является проблемой установщика Node для Windows. Обходной путь — убедиться, что C:Users<user>AppDataRoamingnpm существует и доступен для записи с вашей обычной учетной записью.

No space

npm ERR! Error: ENOSPC, write

Вы пытаетесь установить диск,на котором либо нет места,либо нет разрешения на запись.

  • Освободите место на диске или
  • Установите папку tmp где-нибудь с большим пространством: npm config set tmp /path/to/big/drive/tmp или
  • Соберите Node самостоятельно и установите его где-нибудь,где есть место для записи с большим количеством места.

No git

npm ERR! not found: git
ENOGIT

Вам необходимо установить git . Или вам может потребоваться добавить информацию о git в свой профиль npm. Вы можете сделать это из командной строки или на веб-сайте. Для получения дополнительной информации см. « Управление настройками вашего профиля ».

Запуск блока Vagrant на Windows не удается из-за проблем с длиной пути

@drmyersii прошел через много мучительных проб и ошибок, чтобы предложить рабочее решение, включающее длинные пути Windows и некоторую настраиваемую конфигурацию Vagrant:

Это коммит, в котором я его реализовал , но я опубликую здесь основной фрагмент кода:

config.vm.provider "virtualbox" do |v|
    v.customize ["sharedfolder", "add", :id, "--name", "www", "--hostpath", (("//?/" + File.dirname(__FILE__) + "/www").gsub("/","\"))]
end

config.vm.provision :shell, inline: "mkdir /home/vagrant/www"
config.vm.provision :shell, inline: "mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` > www /home/vagrant/www", run: "always"

В приведенном выше коде я добавляю \? К абсолютному пути текущего каталога. Это фактически заставит Windows API разрешить увеличение переменной MAX_PATH (обычно не более 260). Подробнее о максимальном пути . Это происходит во время создания общей папки, которая намеренно обрабатывается VBoxManage, а не методом Vagrant «synced_folder». Последний пункт довольно понятен; мы создаем новую общую папку, а затем убеждаемся, что она монтируется каждый раз, когда к машине обращаются или касаются, поскольку Vagrant любит перезагружать свои монтированные / общие папки при каждой загрузке.

npm использует только git: и ssh+git: URL-адреса для репозиториев GitHub, нарушая прокси

@LaurentGoderre исправил это с помощью некоторых уловок Git :

Я исправил эту проблему для нескольких своих коллег,запустив следующие две команды:

git config --global url."https://github.com/".insteadOf git@github.com:
git config --global url."https://".insteadOf git:

Одна вещь, которую мы заметили, заключается в том, что используемый .gitconfig не всегда является ожидаемым, поэтому, если вы находитесь на машине, которая изменила домашний путь к общему диску, вам необходимо убедиться, что ваш .gitconfig одинаков как на вашем общем диске, так и на в c:users[your user]

SSL Error

npm ERR! Error: 7684:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:opensslssls23_clnt.c:787:

Вы пытаетесь подключить SSL к незашифрованной конечной точке. Чаще всего это связано с ошибкой конфигурации прокси (см. также это полезное, хотя и устаревшее, руководство ). В этом случае вам не нужно отключать strict-ssl — вам может понадобиться настроить файл CA/CA для использования с вашим прокси, но гораздо лучше потратить время на то, чтобы разобраться в этом, чем отключать защиту SSL.

npm ERR! Error: SSL Error: CERT_UNTRUSTED
npm ERR! Error: SSL Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE

Эта проблема может возникнуть, если вы используете Node 0.6. Пожалуйста, обновите до версии 0.8 или выше. Подробности смотрите в этом посте .

Вы также можете попробовать следующие обходные пути: npm config set ca "" или npm config set strict-ssl false

npm ERR! Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN

npm больше не поддерживает самоподписанные сертификаты

Either:

  • обновите свою версию npm npm install npm -g --ca=""
  • указать вашей текущей версии npm использовать известных регистраторов npm config set ca=""

Если это не решит проблему, возможно, у вас прокси для перехвата SSL. (Например, https://github.com/npm/npm/issues/7439#issuecomment-76024878 )

SSL-intercepting proxy

Неразрешенный. См. Https://github.com/npm/npm/issues/9282

Не найдено/Ошибка сервера

npm http 404 https:
npm ERR! fetch failed https:
npm ERR! Error: 404 Not Found
npm http 500 https://registry.npmjs.org/phonegap
  • Скорее всего, это временный сбой реестра npm. Проверьте статус сервера npm и повторите попытку позже.
  • Если ошибка сохраняется,возможно,опубликованный пакет поврежден.Свяжитесь с владельцем пакета и попросите его опубликовать новую версию пакета.

Invalid JSON

npm ERR! SyntaxError: Unexpected token <
npm ERR! registry error parsing json
  • Возможный временный сбой реестра npm или поврежденный кеш локального сервера. Запустите npm cache clean и / или повторите попытку позже.
  • Это может быть вызвано корпоративными прокси, которые дают HTML-ответы на запросы package.json . Проверьте конфигурацию прокси-сервера npm .
  • Убедитесь, что это не проблема с пакетом, который вы пытаетесь установить (например, недопустимый package.json ).

Многие ошибки ENOENT / ENOTEMPTY в выводе

npm написан для эффективного использования ресурсов при установке, и отчасти это связано с тем, что он пытается делать столько вещей одновременно, сколько это возможно. Иногда это приводит к состояниям гонки и другим проблемам синхронизации. Начиная с npm 2.0.0, было решено очень большое количество этих проблем. Если в выводе журнала вы видите ENOENT lstat , ENOENT chmod , ENOTEMPTY unlink или что-то подобное, попробуйте обновить npm до последней версии. Если проблема не исчезнет, ​​посмотрите npm / npm # 6043 и посмотрите, обсуждал ли кто-нибудь вашу проблему.

cb() never called! при использовании термоусадочных зависимостей

Взгляните на выпуск # 5920 .Мы работаем над исправлением этого, но это довольно сложное состояние гонки, и это отнимает у нас немного времени. Вы можете попробовать переместить файл npm-shrinkwrap.json в сторону, пока мы не исправим это.Это было исправлено в версиях npm новее, чем npm@2.1.5 , поэтому обновите до npm@latest .

npm login ошибки входа в npm

Иногда npm login завершается неудачно без очевидной причины. Первое, что нужно сделать, это войти в систему на https://www.npmjs.com/login и убедиться, что ваш адрес электронной почты на npmjs.com совпадает с адресом электронной почты, который вы указываете для npm login в npm .

Если проблема не в этом или вы видите сообщение "may not mix password_sha and pbkdf2" , то

  1. Авторизуйтесь на https://npmjs.com/
  2. Смените пароль на https://npmjs.com/password — вы даже можете «сменить» его на тот же пароль
  3. Очистите поля, связанные с входом в систему, из ~/.npmrc , например, запустив sed -ie '/registry.npmjs.org/d' ~/.npmrc
  4. npm login

и в целом,похоже,это работает.

Историю этой проблемы см. На https://github.com/npm/npm/issues/6641#issuecomment-72984009 .

npm зависает в Windows на addRemoteTarball

Проверьте, установлены ли в вашем .npmrc два временных каталога :

Найдите строки, определяющие переменную конфигурации tmp . Если вы найдете более одного, удалите все, кроме одного.

См. Https://github.com/npm/npm/issues/7590 для получения дополнительной информации об этой необычной проблеме.

npm не запускает последнюю версию на машине с Windows

См. Раздел о Windows здесь .

Random Errors—One Place to Start

  • Some strange issues can be resolved by simply running npm cache clean and trying again.
  • If you are having trouble with npm install, use the -verbose option to see more details.

No compatible version found

You have an outdated npm. Please update to the latest stable npm.

Permissions Errors

Please see the discussions in Chapter 2 and Chapter 3 about ways to avoid permissions errors.

Error: ENOENT, stat 'C:Users<user>AppDataRoamingnpm' on Windows 7

This is a consequence of joyent/node#8141, and is an issue with the Node installer for Windows. The workaround is to ensure that C:Users<user>AppDataRoamingnpm exists and is writable with your normal user account.

No space

npm ERR! Error: ENOSPC, write

You are trying to install on a drive that either has no space, or has no permission to write.

  • Free some disk space or
  • Set the tmp folder somewhere with more space: npm config set tmp /path/to/big/drive/tmp or
  • Build Node yourself and install it somewhere writable with lots of space.

No git

npm ERR! not found: git
ENOGIT

You need to install git. Or, you may need to add your git information to your npm profile. You can do this from the command line or from the website.

running a Vagrant box on Windows fails due to path length issues

@drmyersii went through what sounds like a lot of painful trial and error to come up with a working solution involving Windows long paths and some custom Vagrant configuration:

This is the commit that I implemented it in, but I’ll go ahead and post the main snippet of code here:

config.vm.provider "virtualbox" do |v|
    v.customize ["sharedfolder", "add", :id, "--name", "www", "--hostpath", (("//?/" + File.dirname(__FILE__) + "/www").gsub("/","\"))]
end
 
config.vm.provision :shell, inline: "mkdir /home/vagrant/www"
config.vm.provision :shell, inline: "mount -t vboxsf -o uid=`id -u vagrant`,gid=`getent group vagrant | cut -d: -f3` > www /home/vagrant/www", run: "always"

In the code above, I am appending \? to the current directory absolute path. This will actually force the Windows API to allow an increase in the MAX_PATH variable (normally capped at 260). Read more about max path. This is happening during the sharedfolder creation which is intentionally handled by VBoxManage and not Vagrant’s «synced_folder» method. The last bit is pretty self-explanatory; we create the new shared folder and then make sure it’s mounted each time the machine is accessed or touched since Vagrant likes to reload its mounts/shared folders on each load.

npm only uses git: and ssh+git: URLs for GitHub repos, breaking proxies

@LaurentGoderre fixed this with some Git trickery:

I fixed this issue for several of my colleagues by running the following two commands:

git config --global url."https://github.com/".insteadOf [email protected]:
git config --global url."https://".insteadOf git://

One thing we noticed is that the .gitconfig used is not always the one expected so if you are on a machine that modified the home path to a shared drive, you need to ensure that your .gitconfig is the same on both your shared drive and in c:users[your user]

SSL Error

npm ERR! Error: 7684:error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol:opensslssls23_clnt.c:787:

You are trying to talk SSL to an unencrypted endpoint. More often than not, this is due to a proxy configuration error (see also this helpful, if dated, guide). In this case, you do not want to disable strict-ssl – you may need to set up a CA / CA file for use with your proxy, but it’s much better to take the time to figure that out than disabling SSL protection.

npm ERR! Error: SSL Error: CERT_UNTRUSTED
npm ERR! Error: SSL Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE

This problem will happen if you’re running Node 0.6. Please upgrade to node 0.8 or above. See this post for details.

You could also try these workarounds: npm config set ca "" or npm config set strict-ssl false

npm ERR! Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN

npm no longer supports its self-signed certificates

Either:

  • upgrade your version of npm npm install npm -g --ca=""
  • tell your current version of npm to use known registrars npm config set ca=""

If this does not fix the problem, then you may have an SSL-intercepting proxy. (For example, https://github.com/npm/npm/issues/7439#issuecomment-76024878)

SSL-intercepting proxy

Unsolved. See https://github.com/npm/npm/issues/9282

Not found / Server error

npm http 404 https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.7.0.tgz
npm ERR! fetch failed https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.7.0.tgz
npm ERR! Error: 404 Not Found
npm http 500 https://registry.npmjs.org/phonegap
  • It’s most likely a temporary npm registry glitch. Check npm server status and try again later.
  • If the error persists, perhaps the published package is corrupt. Contact the package owner and have them publish a new version of the package.

Invalid JSON

Error: Invalid JSON
npm ERR! SyntaxError: Unexpected token <
npm ERR! registry error parsing json
  • Possible temporary npm registry glitch, or corrupted local server cache. Run npm cache clean and/or try again later.
  • This can be caused by corporate proxies that give HTML responses to package.json requests. Check npm’s proxy configuration.
  • Check that it’s not a problem with a package you’re trying to install (e.g. invalid package.json).

Many ENOENT / ENOTEMPTY errors in output

npm is written to use resources efficiently on install, and part of this is that it tries to do as many things concurrently as is practical. Sometimes this results in race conditions and other synchronization issues. As of npm 2.0.0, a very large number of these issues were addressed. If you see ENOENT lstat, ENOENT chmod, ENOTEMPTY unlink, or something similar in your log output, try updating npm to the latest version. If the problem persists, look at npm/npm#6043 and see if somebody has already discussed your issue.

cb() never called! when using shrinkwrapped dependencies

Take a look at issue #5920. We’re working on fixing this one, but it’s a fairly subtle race condition and it’s taking us a little time. You might try moving your npm-shrinkwrap.json file out of the way until we have this fixed. This has been fixed in versions of npm newer than [email protected], so update to [email protected].

npm login errors

Sometimes npm login fails for no obvious reason. The first thing to do is to log in at https://www.npmjs.com/login and check that your e-mail address on npmjs.com matches the email address you are giving to npm login.

If that’s not the problem, or if you are seeing the message "may not mix password_sha and pbkdf2", then

  1. Log in at https://npmjs.com/
  2. Change password at https://npmjs.com/password – you can even «change» it to the same password
  3. Clear login-related fields from ~/.npmrc – e.g., by running sed -ie '/registry.npmjs.org/d' ~/.npmrc
  4. npm login

and it generally seems to work.

See https://github.com/npm/npm/issues/6641#issuecomment-72984009 for the history of this issue.

npm hangs on Windows at addRemoteTarball

Check if you have two temp directories set in your .npmrc:

> npm config ls -l

Look for lines defining the tmp config variable. If you find more than one, remove all but one of them.

See https://github.com/npm/npm/issues/7590 for more about this unusual problem.

Why isn’t npm running the latest version on my Windows machine?

See the section about Windows here.

Понравилась статья? Поделить с друзьями:
  • Error code enoent
  • Error code elifecycle 21 error errno 1
  • Error code ejsonparse
  • Error code ebadplatform
  • Error code e53d989a9e2d47bf