I have created a macOS app with Electron.
The app runs without any problem if I build it and run it locally.
But when Apple tries to run they encounter a problem that gives them this error.
[2021-06-09 10:59:19.217] [info] ----------> start_server
[2021-06-09 10:59:19.218] [info] 3000
[2021-06-09 10:59:19.221] [info] Error while starting server: listen EPERM: operation not permitted 0.0.0.0:3000
[2021-06-09 10:59:19.222] [info] Error caught: listen EPERM: operation not permitted 0.0.0.0:3000
[2021-06-09 10:59:19.222] [info] Error stack : Error: listen EPERM: operation not permitted 0.0.0.0:3000
I’m trying to start a http server with this code:
module.exports = {
startServer: async () => {
_port = await UtilityService.getPort();
console.log(_port);
return new Promise((resolve, reject) => {
httpServer.on('error', error => {
console.log('Error while starting server: ', error.message);
onError(error);
reject(error);
});
httpServer.listen(_port, () => {
console.log('HTTP Server listening on http://localhost:' + _port + '/');
resolve();
});
})
},
https://github.com/mattehalen/Scheduled-countdown/blob/master/src/server.js
Как исправить ошибку npm! Ошибка: EPERM: операция не разрешена, переименовать
Я только что обновил npm
к 5.4.0
. Теперь, когда я хочу установить пакет npm, я получаю следующую ошибку:
D:SourcesDownloadCmsMd.DownloadWeb.Angular>npm install [email protected] --save npm ERR! path D:SourcesDownloadCmsMd.DownloadWeb.Angularnode_modulesfseventsnode_modulesabbrevpackage.json npm ERR! code EPERM npm ERR! errno -4048 npm ERR! syscall unlink npm ERR! Error: EPERM: operation not permitted, unlink 'D:SourcesDownloadCmsMd.DownloadWeb.Angularnode_modulesfseventsnode_modulesabbrevpackage.json' npm ERR! at Error (native) npm ERR! { Error: EPERM: operation not permitted, unlink 'D:SourcesDownloadCmsMd.DownloadWeb.Angularnode_modulesfseventsnode_modulesabbrevpackage.jso n' npm ERR! at Error (native) npm ERR! stack: 'Error: EPERM: operation not permitted, unlink 'D:\Sources\DownloadCms\Md.Download\Web.Angular\node_modules\fsevents\node_modules\ab brev\package.json'n at Error (native)', npm ERR! errno: -4048, npm ERR! code: 'EPERM', npm ERR! syscall: 'unlink', npm ERR! path: 'D:\Sources\DownloadCms\Md.Download\Web.Angular\node_modules\fsevents\node_modules\abbrev\package.json' } npm ERR! npm ERR! Please try running this command again as root/Administrator. npm ERR! A complete log of this run can be found in: npm ERR! C:UsersMohammadAppDataRoamingnpm-cache_logs2017-09-03T03_25_50_432Z-debug.log
Я абсолютно уверен, беги CMD
как администратор.
Также я проверил D:SourcesDownloadCmsMd.DownloadWeb.Angularnode_modulesfseventsnode_modulesabbrevpackage.json
, package.json
не существует в пути!
Редактировать: Обновитесь до v5.4.1, все равно получите ту же ошибку, даже невозможно обойтись с —no-optional
1 2 Далее
Это проблема npm 5.4.0 https://github.com/npm/npm/issues/18287
Обходные пути
- перейти на 5,3
- попробуйте запустить с —no-optional, т.е.
npm install --no-optional
- 7
--no-optional
полностью прибил для меня (@ 5.4.1)! - 10 если вы открыли
VSCode
затем закройте его и попробуйте запуститьnpm
команда будет установлена определенно, переход на более раннюю версию не является решением. - 4 Закрытие VS Code и запуск
npm i
извне работал у меня.
Я смог исправить это, запустив командную строку / bash от имени администратора и закрыв VSCode! Похоже, что VSCode заблокировал некоторые файлы. Возможно, что-то еще может заблокировать эти файлы за вас.
- 11 Спасибо! В моем случае это была Visual Studio 2015, которая блокировала некоторые файлы.
- Ага. Спасибо. Очень просто. Закрыл VS Code и решил все мои проблемы.
- 2 В моем случае Process Explorer неизменно сообщает мне, что виновник блокировки файлов
npm
пытается удалить … другойnode.exe
процесс, порожденныйnpm
Бегnpm
! О, радость, этот инструмент не перестает удивлять… (это в Windows 10, Node 12.11.0, npm 6.11.3) - почему, черт возьми
vscode
не удается установить угловое приложение? - +1 Для закрытия любых запущенных процессов, которые могут зависать в файле — у меня была запущена служба vue-cli-service. Закрытие, которое решило это для меня.
Если вы перейдете на версию 5.3 и получите такую же ошибку в Windows, как и я.
После нескольких часов работы с версиями npm я нашел следующее решение:
1. Загрузите последнюю рекомендованную версию nodejs
, в эти дни node-v6.11.3-x64
2. Удалить nodejs
с этим.
3. Перейти к C:Users{YourUsername}AppDataRoaming
папку и удалить npm
а также npm-cache
папки
4. Запустить установщик nodejs
снова и установите его
5 Обновите npm до 5.3 с помощью npm i -g [email protected]
командная строка
Теперь вы должны использовать npm без каких-либо проблем.
Я исправил, понизив npm с 5.4.0 до версии 5.3
npm i -g [email protected]
Надеюсь, это поможет вам
Я попробовал это решение, найденное в блоге Как исправить Node.js
просто используйте
npm cache clean
в окнах, если он отказывается использовать
npm cache clean --force
- 1 У меня не работает. Windows в CI на VSTS (теперь Azure DevOps)
У меня была такая же проблема в Windows.
Источник проблемы прост, это разрешение доступа к папкам и файлам.
В папке вашего проекта вам нужно
- После клонирования проекта измените свойства папки и измените права пользователя (предоставьте полный доступ текущему пользователю).
- Удалите параметр только для чтения из папки проекта. (Шаги 1 и 2 занимают много времени, потому что они копируются на все дерево ниже).
- Внутри папки проекта переустановите узел (npm install переустановить -g)
- Отключите антивирус. (по желанию)
- Отключите брандмауэр. (по желанию)
- Перезагрузите компьютер.
- Очистить кеш npm (очистить npm)
- Установите зависимости вашего проекта (установка npm)
После этого ошибка «Ошибка: EPERM: операция не разрешена, разорвать связь«больше не будет отображаться.
Не забудьте повторно активировать брандмауэр и антивирус при необходимости.
У меня была такая же проблема, и все, что мне нужно было сделать, это войти в npm
npm login
или альтернативно
npm add user
// обратитесь к документации по параметрам
Закройте все IDE, например код Visual Studio. запустите команду npm install через командную строку node.js. Наслаждайтесь !
- В некоторых случаях требуется перезагрузка системы.
- Также проверьте файл .NPMRC
кеш чист и npm
обновить до последней версии с принудительной работой для меня
npm cache clean --force npm install -g [email protected] --force
В моем случае проблема заключалась в том, Машинопись не устанавливал. Хотя я установил Node и Angular. Чтобы проверить, установили ли вы машинописный текст или нет
Run this command: tsc -v
Если нет, то для установки машинописи
Run this command: npm install -g typescript
И, наконец, установить необходимые зависимости
Run this command: npm install
в корневой папке проекта.
—- Надеюсь, это кому-то поможет —-
Для меня это сработало в bash из пакета git попробуйте:
C:Program FilesGitbinbash.exe
тогда:
npm install [email protected]
Кажется, есть много решений, которые работали с понижением версий npm. Для меня решение было
npm install -force
Я попробовал понизить версию npm, изменив конфигурацию префикса npm, чтобы он соответствовал каталогу npm, и очистил кеш. Ни один из них не работал, но, очевидно, они работали для других, так что, возможно, стоит попробовать.
Для меня в Windows проблема была слишком длинная длина пути. Я переместил проект на путь меньшей длины, и он сработал.
У меня были эти логи в Windows. Я сделал следующее
- Закройте код Visual Studio
- Запустите командную строку от имени администратора
Если все вышеперечисленное не помогло вам, возможно, вы захотите
- перезагрузите вашу систему
- запустить командную строку от имени администратора
- запустите команду npm
Удаление package-lock.json устранило это для меня.
та же ошибка приходит ко мне, когда я обновляю версию npm до последней версии 5.4, даунгрейд до версии 5.3.0 полезен. ошибка возникает из npm 5.4, вы можете проверить ее в выпусках в npm 5.4
npm install [email protected] -g
Исправлено в NPM 5.6.0
Обновление до NPM 5.6.0 решило для меня проблему.
Я хотел запустить npm install с внешнего жесткого диска, так как именно здесь я сохранил свое рабочее пространство с кодом. ОС Windows 10.
Но я получал ту же ошибку, что и исходный пост. Ни один из предыдущих ответов у меня не работал, я перепробовал их все:
- удаление nodejs, а затем повторная установка
- удаление nodejs, а затем понижение / установка более ранней версии nodejs.
- npm install -force
- удаление папок из C: Users {YourUsername} AppData Roaming … npm и npm-cache, а затем повторная установка.
- очистка кеша npm —force
- очистка кеша npm
- npm install —g или npm install —global
Для меня сработало следующее:
- скопируйте папку из C: Program Files nodejs в D: Program Files nodejs
- Затем перейдите в Панель управления Система и безопасность Система
- Расширенные настройки системы
- Переменные среды
- Системные переменные
- Дважды щелкните Путь
- Добавить новый путь
- D: Program Files nodejs
- Нажмите ОК
- перезагрузите компьютер.
- попробуйте установить npm из D: Drive
После всех попыток, включая обновление node / npm, очистку кеша и возврат кода, ничего не помогло, кроме одной простой вещи: Отключение защиты в реальном времени в Windows 10 во время разработки / сборки. Похоже, последние обновления сделали его супер агрессивным.
я использую VsCode
и решил эту проблему, остановив сервер приложений, и они запустили npm install
. Есть файлы, заблокированные сервером приложений.
Не нужно закрывать IDE, просто убедитесь, что другой процесс не блокирует некоторые файлы в ваших проектах.
Мой был в результате открытия папки моего проекта двумя разными терминалами. я решено это от закрытие всех работающих терминалов (код vs был исключен) и повторное выполнение команды установки.
Я надеюсь, что это помогает кому-то.
NB: удаление node_modules не решило эту проблему.
Для окон,
- Загрузите последнюю рекомендованную версию
nodejs
, в эти дниnode-v6.11.3-x64
- Удалите с ним nodejs.
- Перейти к
C:Users{YourUsername}AppDataRoaming
папку и удалитьnpm
а такжеnpm-cache
папки - Запустить установщик
nodejs
снова и установите его - По умолчанию
npm 3.10.10
должен быть установлен вместе сnode-v6.11.3-x64
. - Это сработало для меня с
npm 3.10.10
но не работал с5.3.X
. Также он не работал с более поздними версиями узла (см. Вышеnode-v6.11.3-x64
)
npm cache verify
решил мою проблему. Я делал: ng new my-app
и я столкнулся с аналогичной ошибкой
У меня версия узла: 10.16.0
npm v 6.9.0
Моя проблема заключалась в выполнении команды (npm audit fix all). Решил при закрытии VSCODE и без проблем повторно выполнил команду.
Я просто полностью выключил, НЕ переходил в спящий режим, свою машину и перезапустил. Запустил CMD от имени администратора и использовал команду установки npm. Это сработало.
В моем случае я столкнулся с аналогичной проблемой при запуске нескольких экземпляров ‘npm install’ на виртуальной машине, используемой для сборки (Windows)
Поскольку это была виртуальная машина, которая использовалась только для сборки, никакая другая программа не блокировала файлы. Я пытался отключить различные настройки антивируса, но они не помогли. «npm cache clear» и «npm cache verify» работали, но для меня это не было правильным решением, так как я не могу угадать, когда кто-то запустит задание сборки от Jenkins для другого выпуска / среды, что приведет к нескольким экземплярам ‘npm install’ и, следовательно, Я не могу добавить его в сценарий сборки, и я не могу войти в виртуальную машину и каждый раз очищать / удалять папки кеша вручную.
Наконец, после некоторого исследования я закончил запуском «npm install» с отдельным путем кеширования для каждого задания, используя следующую команду:
npm install --cache path/to/some/folder
Поскольку все задания, выполняющиеся одновременно, теперь имели отдельный путь кэширования, а не общий глобальный путь (Users / AppData / Roaming /), эта проблема была исправлена, поскольку задания больше не пытались заблокировать и получить доступ к одному и тому же файлу, из общего кеша npm.
Обратите внимание, что вы можете установить один пакет с путем кэширования следующим образом:
npm install packageName --cache path/to/some/folder
Мне не удалось найти этот способ указать путь к кешу в документации npm, но я попробовал, и он сработал. Я использую npm6 и похоже, что он работает с npm5.
[Обратитесь: Как указать папку кеша в npm5 при команде установки?
Это решение должно работать и для других сценариев, хотя может подойти, а может и не подойти.
npm login
требуется до publish
Это единственное, что у меня сработало:
npm cache clean --force npm install -g [email protected] --force rm package-lock.json npm i -force
У меня такая же проблема, просто выполняя установку npm. Запускайте с отключенным антивирусом (если вы используете Защитник Windows, отключите защиту в реальном времени и защиту на основе облака). Это сработало для меня!
1 2 Далее
Tweet
Share
Link
Plus
Send
Send
Pin
What version of Next.js are you using?
12.0.1
What version of Node.js are you using?
14.17.3
What browser are you using?
Chrome, Safari, Firefox, Edge
What operating system are you using?
Windows10, Ubuntu18 — 20, Ios
How are you deploying your application?
VPS — custom server — NginX proxy
Describe the Bug
after upgrading to Next 12.0.1 everything was fine but at the build time I got a message :
(warn — Disabled SWC as a replacement for Babel because of custom Babel configuration «
.babelrc» https://nextjs.org/docs/messages/swc-disabled
)
about that next won’t use SWC because there is a .babelrc file. I removed the usage and the .babelrc file itself. now I do not have any issue with development mode but when I run the next build I get this error
info — Creating an optimized production build ..events.js:352
throw er; // Unhandled ‘error’ event
^
Error: EPERM: operation not permitted, open ‘I:*.nexttrace’
Emitted ‘error’ event on WriteStream instance at:
at I:*node_modulesnextdistcompiled@vercelnftindex.js:1:287421
at I:*node_modulesnextdistcompiled@vercelnftindex.js:1:287860
at FSReqCallback.oncomplete (fs.js:180:23) {
errno: -4048,
code: ‘EPERM’,
syscall: ‘open’,
path: ‘I:*.nexttrace’
}
Expected Behavior
I expect the next build has access to trace file so the build runs with no issue
To Reproduce
The first time I use nuXT, the environment has not been placed, and various reports.
One of the following prompts:
Error: EPERM: operation not permitted
Means permissions are not allowed. I used a few ways, and this method is now a bit response, and I record it.
The solution is as follows:
1. Delete the package-lock.json file under the project root directory (uncertain or not deleted);
2. Delete the Node_Modules folder
2. Open the terminal and run NPM Cache Clean —force;
3. Perform CNPM Install in the terminal;
The first execution of CNPM INSTALL still has problems, did not understand what it means
The second execution of CNPM INSTALL seems to solve the problem.
As shown in the figure below (red is the command, the magenta success prompts):
Windows PowerShell Copyright (C) Microsoft Corporation. all rights reserved. Try a new cross-platform PowerShell https://aka.ms/pscore6 PS D:heimaguili_vuevue-admin-front-nuxt> npm cache clean --force npm WARN using --force I sure hope you know what you are doing. PS D:heimaguili_vuevue-admin-front-nuxt> cnpm install [1/7] Installing [email protected]^3.0.2platform unsupported [email protected] › @nuxt/[email protected] › [email protected] › [email protected]~2.1.2 Package require os(darwin) not compatible with your platform(win32) | [1/7] Installing [email protected]~1.5.0[[email protected]~2.1.2] optional install error: Package require os(darwin) not compatible with your platform(win32) - [6/7] Installing [email protected]^2.0.0 WARN node unsupported "[email protected]" is incompatible with [email protected] › @nuxt/[email protected] › [email protected] › [email protected] › [email protected] › [email protected]^2.0.0, expected [email protected]<8.10.0 | [6/7] Installing [email protected]^2.0.1platform unsupported [email protected] › @nuxt/[email protected] › [email protected] › [email protected] › [email protected] › [email protected] › [email protected] › [email protected]^1.2.7 Package require os(darwin) not compatible with your platform(win32) / [6/7] Installing [email protected]^5.0.1[[email protected]^1.2.7] optional install error: Package require os(darwin) not compatible with your platform(win32) √ Installed 7 packages √ Linked 933 latest versions [1/3] scripts.postinstall [email protected] › @nuxt/[email protected] › [email protected] › [email protected]^2.6.1 run "node ./postinstall.js", root: "D:\heima\guili_vue\vue-admin-front-nuxt\node_modules\[email protected]@ejs" Thank you for installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/) [1/3] scripts.postinstall [email protected] › @nuxt/[email protected] › [email protected] › [email protected]^2.6.1 finished in 126ms [2/3] scripts.postinstall [email protected] › @nuxt/[email protected] › @nuxt/[email protected] › [email protected]^2.6.5 run "node -e "try{require('./postinstall')}catch(e){}"", root: "D:\heima\guili_vue\vue-admin-front-nuxt\node_modules\[email protected]@core-js" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) [2/3] scripts.postinstall [email protected] › @nuxt/[email protected] › @nuxt/[email protected] › [email protected]^2.6.5 finished in 139ms [3/3] scripts.postinstall [email protected]^2.0.0 run "opencollective || exit 0", root: "D:\heima\guili_vue\vue-admin-front-nuxt\node_modules\[email protected]@nuxt" :-: .==-+: .==. :+- .-=- .==. :==++-+=. :==. -**: :+=. :+- :*+++. .++. :+- -*= .++: .=+. -+: =*- .+*: .=+: -+: .=*- .=*- =+: .==: .+*: -*- -+- .=+:.....:+*-.........:=*=..=*- .-=------=++============++====: Thanks for installing nuxtjs Please consider donating to our open collective to help us maintain this package. Donate: https://opencollective.com/nuxtjs/donate [3/3] scripts.postinstall [email protected]^2.0.0 finished in 3s √ Run 3 scripts peerDependencies link [email protected]5.5.2 in D:heimaguili_vuevue-admin-front-nuxtnode_modules[email protected]@ajv-keywords unmet with D:heimaguili_vuevue-admin-front-nuxtnode_modulesajv(6.12.4) deprecate [email protected]4.19.1 › [email protected] › [email protected] › [email protected]^0.3.1 CircularJSON is in maintenance only, flatted is its successor. deprecate [email protected]2.14.3 › @nuxt/[email protected] › [email protected] › [email protected] › [email protected] › [email protected] › [email protected]^2.1.8 Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies. deprecate [email protected]2.14.3 › @nuxt/[email protected] › [email protected] › [email protected] › [email protected] › [email protected] › [email protected] › [email protected]^1.2.7 fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2. [email protected]0.5.3 › [email protected]^0.1.0 Please see https://github.com/lydell/urix#deprecated deprecate [email protected] › @nuxt/[email protected] › [email protected] › [email protected] › [email protected] › [email protected] › [email protected] › [email protected] › [email protected]^0.2.1 https://github.com/lydell/resolve-url#deprecated deprecate [email protected] › @nuxt/[email protected] › @nuxt/[email protected] › [email protected]^2.6.5 [email protected]<3 is no longer maintained and not recommended for usage due to the number of issues. Please, upgrade your dependencies to the actual version of [email protected]. Recently updated (since 2020-08-10): 22 packages (detail see file D:heimaguili_vuevue-admin-front-nuxtnode_modules.recently_updates.txt) Today: → [email protected]^2.0.0(2.14.3) (01:04:22) → [email protected]2.14.3 › @nuxt/[email protected](2.14.3) (01:03:34) → [email protected]2.14.3 › @nuxt/[email protected](2.14.3) (01:03:51) → [email protected]2.14.3 › @nuxt/[email protected](2.14.3) (01:03:38) → [email protected]2.14.3 › @nuxt/[email protected](2.14.3) (01:03:47) → [email protected]2.14.3 › @nuxt/[email protected](2.14.3) (01:04:18) → [email protected]2.14.3 › @nuxt/[email protected] › @nuxt/[email protected](2.14.3) (01:04:04) → [email protected]2.14.3 › @nuxt/[email protected] › @nuxt/[email protected](2.14.3) (01:04:09) → [email protected]2.14.3 › @nuxt/[email protected] › @nuxt/[email protected](2.14.3) (01:03:43) → [email protected]2.14.3 › @nuxt/[email protected] › @nuxt/[email protected](2.14.3) (01:03:55) → [email protected]2.14.3 › @nuxt/[email protected] › @nuxt/[email protected](2.14.3) (01:04:13) → [email protected]2.14.3 › @nuxt/[email protected] › @nuxt/[email protected](2.14.3) (01:03:30) √ All packages installed (1097 packages installed from npm registry, used 17s(network 13s), speed 184.65kB/s, json 940(2.29MB), tarball 0B) PS D:heimaguili_vuevue-admin-front-nuxt> cnpm install √ Installed 7 packages √ Linked 0 latest versions √ Run 0 scripts √ All packages installed (used 13ms(network 9ms), speed 0B/s, json 0(0B), tarball 0B) PS D:heimaguili_vuevue-admin-front-nuxt>
Then I execute the start command again
As shown in the figure below (red is the command, the magenta success prompts):
PS D:heimaguili_vuevue-admin-front-nuxt> npm run dev > [email protected] dev D:heimaguili_vuevue-admin-front-nuxt > nuxt i NuxtJS collects completely anonymous data about usage. 14:31:22 This will help us improving Nuxt developer experience over the time. Read more on https://git.io/nuxt-telemetry ? Are you interested in participation? Yes WARN Address localhost:3000 is already in use. 14:32:26 i Trying a random port... 14:32:26 ╭────────────────────────────────────────╮ │ │ │ Nuxt.js @ v2.14.3 │ │ │ │ ▸ Environment: development │ │ ▸ Rendering: server-side │ │ ▸ Target: server │ │ │ │ Listening: http://localhost:60774/ │ │ │ ╰────────────────────────────────────────╯ i Preparing project for development 14:32:27 i Initial build may take a while 14:32:27 √ Builder initialized 14:32:27 √ Nuxt files generated 14:32:27 √ Client Compiled successfully in 5.43s √ Server Compiled successfully in 5.03s i Waiting for file changes 14:32:35 i Memory usage: 204 MB (RSS: 275 MB) 14:32:35 i Listening on: http://localhost:60774/ 14:32:35 ERROR [Vue warn]: Property or method "name" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. found in ---> <Pages/index.vue> at pages/index.vue <Nuxt> <Layouts/default.vue> at layouts/default.vue <Root> ERROR [Vue warn]: Property or method "description" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties. found in ---> <Pages/index.vue> at pages/index.vue <Nuxt> <Layouts/default.vue> at layouts/default.vue <Root>
Then you can access it.
Access the following URL, but I don’t know why the port number is this, it has changed several times.
Figure 1:
Figure II:
For the first time, it seems that it is successful.
Install slide plugin
I have also met the problem,Execute both sidesThe following code is successful
Stop the project before executing the command
npm install vue-awesome-swiper
Figure:
Terminate batch operation (Y / N)? y PS D:heimaguili_vuevue-admin-front-nuxt> npm install vue-awesome-swiper npm WARN deprecated [email protected]1.2.13: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected]^1.2.7 (node_modules[email protected]@chokidarnode_modulesfsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) 。
。
. I omit a lot of lines here
。
。 npm WARN @vue/[email protected] requires a peer of @babel/[email protected]^7.0.0-0 but none is installed. You must install peer dependencies yourself. npm WARN @babel/[email protected] requires a peer of @babel/[email protected]^7.0.0-0 but none is installed. You must install peer dependencies yourself. npm WARN @vue/[email protected] requires a peer of @babel/[email protected]^7.0.0-0 but none is installed. You must install peer dependencies yourself. npm WARN webpack-external-import@2.2.4 requires a peer of [email protected]^4.40.2 but none is installed. You must install peer dependencies yourself. npm WARN vue[email protected] requires a peer of [email protected]^5.2.0 but none is installed. You must install peer dependencies yourself. npm WARN vue[email protected] requires a peer of [email protected].x but none is installed. You must install peer dependencies yourself. npm ERR! code ENOENT npm ERR! syscall rename npm ERR! path D:heimaguili_vuevue-admin-front-nuxtnode_modules[email protected]@shebang-commandnode_modulesshebang-regex npm ERR! dest D:heimaguili_vuevue-admin-front-nuxtnode_modules[email protected]@shebang-commandnode_modulesshebang-regex npm ERR! errno -4058 npm ERR! enoent ENOENT: no such file or directory, rename 'D:heimaguili_vuevue-admin-front-nuxtnode_modules[email protected]@shebang-commandnode_modulesshebang-regex' -> 'D:heimaguili_vuevue-admin-front-nuxtnode_modules[email protected]@shebang-commandnode_modulesshebang-regex' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent npm ERR! A complete log of this run can be found in: npm ERR! C:UsersoorAppDataRoamingnpm-cache_logs2020-08-17T07_44_33_049Z-debug.log PS D:heimaguili_vuevue-admin-front-nuxt> npm install vue-awesome-swiper npm WARN registry Unexpected warning for https://registry.npmjs.org/: Miscellaneous Warning ETIMEDOUT: request to https://registry.npmjs.org/vue-awesome-swiper failed, reason: connect ETIMEDOUT 104.16.17.35:443 npm WARN registry Using stale data from https://registry.npmjs.org/ due to a request error during revalidation. npm notice created a lockfile as package-lock.json. You should commit this file. npm WARN vue[email protected] requires a peer of [email protected]^5.2.0 but none is installed. You must install peer dependencies yourself. npm WARN vue[email protected] requires a peer of [email protected].x but none is installed. You must install peer dependencies yourself. + [email protected] added 1 package from 1 contributor and removed 1954 packages in 401.678s
You will encounter various kinds of errors while developing Node.js
applications, but most can be avoided or easily mitigated with the right coding
practices. However, most of the information to fix these problems are currently
scattered across various GitHub issues and forum posts which could lead to
spending more time than necessary when seeking solutions.
Therefore, we’ve compiled this list of 15 common Node.js errors along with one
or more strategies to follow to fix each one. While this is not a comprehensive
list of all the errors you can encounter when developing Node.js applications,
it should help you understand why some of these common errors occur and feasible
solutions to avoid future recurrence.
🔭 Want to centralize and monitor your Node.js error logs?
Head over to Logtail and start ingesting your logs in 5 minutes.
1. ECONNRESET
ECONNRESET
is a common exception that occurs when the TCP connection to
another server is closed abruptly, usually before a response is received. It can
be emitted when you attempt a request through a TCP connection that has already
been closed or when the connection is closed before a response is received
(perhaps in case of a timeout). This exception will usually
look like the following depending on your version of Node.js:
Output
Error: socket hang up
at connResetException (node:internal/errors:691:14)
at Socket.socketOnEnd (node:_http_client:466:23)
at Socket.emit (node:events:532:35)
at endReadableNT (node:internal/streams/readable:1346:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ECONNRESET'
}
If this exception occurs when making a request to another server, you should
catch it and decide how to handle it. For example, you can retry the request
immediately, or queue it for later. You can also investigate your timeout
settings if you’d like to wait longer for the request to be
completed.
On the other hand, if it is caused by a client deliberately closing an
unfulfilled request to your server, then you don’t need to do anything except
end the connection (res.end()
), and stop any operations performed in
generating a response. You can detect if a client socket was destroyed through
the following:
app.get("/", (req, res) => {
// listen for the 'close' event on the request
req.on("close", () => {
console.log("closed connection");
});
console.log(res.socket.destroyed); // true if socket is closed
});
2. ENOTFOUND
The ENOTFOUND
exception occurs in Node.js when a connection cannot be
established to some host due to a DNS error. This usually occurs due to an
incorrect host
value, or when localhost
is not mapped correctly to
127.0.0.1
. It can also occur when a domain goes down or no longer exists.
Here’s an example of how the error often appears in the Node.js console:
Output
Error: getaddrinfo ENOTFOUND http://localhost
at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
errno: -3008,
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'http://localhost'
}
If you get this error in your Node.js application or while running a script, you
can try the following strategies to fix it:
Check the domain name
First, ensure that you didn’t make a typo while entering the domain name. You
can also use a tool like DNS Checker to confirm that
the domain is resolving successfully in your location or region.
Check the host value
If you’re using http.request()
or https.request()
methods from the standard
library, ensure that the host
value in the options object contains only the
domain name or IP address of the server. It shouldn’t contain the protocol,
port, or request path (use the protocol
, port
, and path
properties for
those values respectively).
// don't do this
const options = {
host: 'http://example.com/path/to/resource',
};
// do this instead
const options = {
host: 'example.com',
path: '/path/to/resource',
};
http.request(options, (res) => {});
Check your localhost mapping
If you’re trying to connect to localhost
, and the ENOTFOUND
error is thrown,
it may mean that the localhost
is missing in your hosts file. On Linux and
macOS, ensure that your /etc/hosts
file contains the following entry:
You may need to flush your DNS cache afterward:
sudo killall -HUP mDNSResponder # macOS
On Linux, clearing the DNS cache depends on the distribution and caching service
in use. Therefore, do investigate the appropriate command to run on your system.
3. ETIMEDOUT
The ETIMEDOUT
error is thrown by the Node.js runtime when a connection or HTTP
request is not closed properly after some time. You might encounter this error
from time to time if you configured a timeout on your
outgoing HTTP requests. The general solution to this issue is to catch the error
and repeat the request, preferably using an
exponential backoff
strategy so that a waiting period is added between subsequent retries until the
request eventually succeeds, or the maximum amount of retries is reached. If you
encounter this error frequently, try to investigate your request timeout
settings and choose a more appropriate value for the endpoint
if possible.
4. ECONNREFUSED
The ECONNREFUSED
error is produced when a request is made to an endpoint but a
connection could not be established because the specified address wasn’t
reachable. This is usually caused by an inactive target service. For example,
the error below resulted from attempting to connect to http://localhost:8000
when no program is listening at that endpoint.
Error: connect ECONNREFUSED 127.0.0.1:8000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
Emitted 'error' event on ClientRequest instance at:
at Socket.socketErrorListener (node:_http_client:442:9)
at Socket.emit (node:events:526:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8000
}
The fix for this problem is to ensure that the target service is active and
accepting connections at the specified endpoint.
5. ERRADDRINUSE
This error is commonly encountered when starting or restarting a web server. It
indicates that the server is attempting to listen for connections at a port that
is already occupied by some other application.
Error: listen EADDRINUSE: address already in use :::3001
at Server.setupListenHandle [as _listen2] (node:net:1330:16)
at listenInCluster (node:net:1378:12)
at Server.listen (node:net:1465:7)
at Function.listen (/home/ayo/dev/demo/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/home/ayo/dev/demo/main.js:16:18)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -98,
syscall: 'listen',
address: '::',
port: 3001
}
The easiest fix for this error would be to configure your application to listen
on a different port (preferably by updating an environmental variable). However,
if you need that specific port that is in use, you can find out the process ID
of the application using it through the command below:
Output
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 2902 ayo 19u IPv6 781904 0t0 TCP *:3001 (LISTEN)
Afterward, kill the process by passing the PID
value to the kill
command:
After running the command above, the application will be forcefully closed
freeing up the desired port for your intended use.
6. EADDRNOTAVAIL
This error is similar to EADDRINUSE
because it results from trying to run a
Node.js server at a specific port. It usually indicates a configuration issue
with your IP address, such as when you try to bind your server to a static IP:
const express = require('express');
const app = express();
const server = app.listen(3000, '192.168.0.101', function () {
console.log('server listening at port 3000......');
});
Output
Error: listen EADDRNOTAVAIL: address not available 192.168.0.101:3000
at Server.setupListenHandle [as _listen2] (node:net:1313:21)
at listenInCluster (node:net:1378:12)
at doListen (node:net:1516:7)
at processTicksAndRejections (node:internal/process/task_queues:84:21)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRNOTAVAIL',
errno: -99,
syscall: 'listen',
address: '192.168.0.101',
port: 3000
}
To resolve this issue, ensure that you have the right IP address (it may
sometimes change), or you can bind to any or all IPs by using 0.0.0.0
as shown
below:
var server = app.listen(3000, '0.0.0.0', function () {
console.log('server listening at port 3000......');
});
7. ECONNABORTED
The ECONNABORTED
exception is thrown when an active network connection is
aborted by the server before reading from the request body or writing to the
response body has completed. The example below demonstrates how this problem can
occur in a Node.js program:
const express = require('express');
const app = express();
const path = require('path');
app.get('/', function (req, res, next) {
res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
console.log(err);
});
res.end();
});
const server = app.listen(3000, () => {
console.log('server listening at port 3001......');
});
Output
Error: Request aborted
at onaborted (/home/ayo/dev/demo/node_modules/express/lib/response.js:1030:15)
at Immediate._onImmediate (/home/ayo/dev/demo/node_modules/express/lib/response.js:1072:9)
at processImmediate (node:internal/timers:466:21) {
code: 'ECONNABORTED'
}
The problem here is that res.end()
was called prematurely before
res.sendFile()
has had a chance to complete due to the asynchronous nature of
the method. The solution here is to move res.end()
into sendFile()
‘s
callback function:
app.get('/', function (req, res, next) {
res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
console.log(err);
res.end();
});
});
8. EHOSTUNREACH
An EHOSTUNREACH
exception indicates that a TCP connection failed because the
underlying protocol software found no route to the network or host. It can also
be triggered when traffic is blocked by a firewall or in response to information
received by intermediate gateways or switching nodes. If you encounter this
error, you may need to check your operating system’s routing tables or firewall
setup to fix the problem.
9. EAI_AGAIN
Node.js throws an EAI_AGAIN
error when a temporary failure in domain name
resolution occurs. A DNS lookup timeout that usually indicates a problem with
your network connection or your proxy settings. You can get this error when
trying to install an npm
package:
Output
npm ERR! code EAI_AGAIN
npm ERR! syscall getaddrinfo
npm ERR! errno EAI_AGAIN
npm ERR! request to https://registry.npmjs.org/nestjs failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org
If you’ve determined that your internet connection is working correctly, then
you should investigate your DNS resolver settings (/etc/resolv.conf
) or your
/etc/hosts
file to ensure it is set up correctly.
10. ENOENT
This error is a straightforward one. It means «Error No Entity» and is raised
when a specified path (file or directory) does not exist in the filesystem. It
is most commonly encountered when performing an operation with the fs
module
or running a script that expects a specific directory structure.
fs.open('non-existent-file.txt', (err, fd) => {
if (err) {
console.log(err);
}
});
Output
[Error: ENOENT: no such file or directory, open 'non-existent-file.txt'] {
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: 'non-existent-file.txt'
}
To fix this error, you either need to create the expected directory structure or
change the path so that the script looks in the correct directory.
11. EISDIR
If you encounter this error, the operation that raised it expected a file
argument but was provided with a directory.
// config is actually a directory
fs.readFile('config', (err, data) => {
if (err) throw err;
console.log(data);
});
Output
[Error: EISDIR: illegal operation on a directory, read] {
errno: -21,
code: 'EISDIR',
syscall: 'read'
}
Fixing this error involves correcting the provided path so that it leads to a
file instead.
12. ENOTDIR
This error is the inverse of EISDIR
. It means a file argument was supplied
where a directory was expected. To avoid this error, ensure that the provided
path leads to a directory and not a file.
fs.opendir('/etc/passwd', (err, _dir) => {
if (err) throw err;
});
Output
[Error: ENOTDIR: not a directory, opendir '/etc/passwd'] {
errno: -20,
code: 'ENOTDIR',
syscall: 'opendir',
path: '/etc/passwd'
}
13. EACCES
The EACCES
error is often encountered when trying to access a file in a way
that is forbidden by its access permissions. You may also encounter this error
when you’re trying to install a global NPM package (depending on how you
installed Node.js and npm
), or when you try to run a server on a port lower
than 1024.
fs.readFile('/etc/sudoers', (err, data) => {
if (err) throw err;
console.log(data);
});
Output
[Error: EACCES: permission denied, open '/etc/sudoers'] {
errno: -13,
code: 'EACCES',
syscall: 'open',
path: '/etc/sudoers'
}
Essentially, this error indicates that the user executing the script does not
have the required permission to access a resource. A quick fix is to prefix the
script execution command with sudo
so that it is executed as root, but this is
a bad idea
for security reasons.
The correct fix for this error is to give the user executing the script the
required permissions to access the resource through the chown
command on Linux
in the case of a file or directory.
sudo chown -R $(whoami) /path/to/directory
If you encounter an EACCES
error when trying to listen on a port lower than
1024, you can use a higher port and set up port forwarding through iptables
.
The following command forwards HTTP traffic going to port 80 to port 8080
(assuming your application is listening on port 8080):
sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
If you encounter EACCES
errors when trying to install a global npm
package,
it usually means that you installed the Node.js and npm
versions found in your
system’s repositories. The recommended course of action is to uninstall those
versions and reinstall them through a Node environment manager like
NVM or Volta.
14. EEXIST
The EEXIST
error is another filesystem error that is encountered whenever a
file or directory exists, but the attempted operation requires it not to exist.
For example, you will see this error when you attempt to create a directory that
already exists as shown below:
const fs = require('fs');
fs.mkdirSync('temp', (err) => {
if (err) throw err;
});
Output
Error: EEXIST: file already exists, mkdir 'temp'
at Object.mkdirSync (node:fs:1349:3)
at Object.<anonymous> (/home/ayo/dev/demo/main.js:3:4)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47 {
errno: -17,
syscall: 'mkdir',
code: 'EEXIST',
path: 'temp'
}
The solution here is to check if the path exists through fs.existsSync()
before attempting to create it:
const fs = require('fs');
if (!fs.existsSync('temp')) {
fs.mkdirSync('temp', (err) => {
if (err) throw err;
});
}
15. EPERM
The EPERM
error may be encountered in various scenarios, usually when
installing an npm
package. It indicates that the operation being carried out
could not be completed due to permission issues. This error often indicates that
a write was attempted to a file that is in a read-only state although you may
sometimes encounter an EACCES
error instead.
Here are some possible fixes you can try if you run into this problem:
- Close all instances of your editor before rerunning the command (maybe some
files were locked by the editor). - Clean the
npm
cache withnpm cache clean --force
. - Close or disable your Anti-virus software if have one.
- If you have a development server running, stop it before executing the
installation command once again. - Use the
--force
option as innpm install --force
. - Remove your
node_modules
folder withrm -rf node_modules
and install them
once again withnpm install
.
Conclusion
In this article, we covered 15 of the most common Node.js errors you are likely
to encounter when developing applications or utilizing Node.js-based tools, and
we discussed possible solutions to each one. This by no means an exhaustive list
so ensure to check out the
Node.js errors documentation or the
errno(3) man page for a
more comprehensive listing.
Thanks for reading, and happy coding!
Check Uptime, Ping, Ports, SSL and more.
Get Slack, SMS and phone incident alerts.
Easy on-call duty scheduling.
Create free status page on your domain.
Got an article suggestion?
Let us know
Next article
How to Configure Nginx as a Reverse Proxy for Node.js Applications
→
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Recently, when attempting to use the gulp
command in the Terminal app, I saw an error message saying Error: EPERM: operation not permitted, uv_cwd
. In this tutorial, you’ll learn how to solve this problem.
What causes this error
In my case, the below error appeared when attempting to run the gulp
command inside my app project directory in the Terminal app.
$ gulp build internal/bootstrap/switches/does_own_process_state.js:129 cachedCwd = rawMethods.cwd(); ^ Error: EPERM: operation not permitted, uv_cwd at process.wrappedCwd [as cwd] (internal/bootstrap/switches/does_own_process_state.js:129:28) at Yargs (/usr/local/lib/node_modules/gulp-cli/node_modules/yargs/yargs.js:33:27) at Argv (/usr/local/lib/node_modules/gulp-cli/node_modules/yargs/index.js:11:16) at Object.<anonymous> (/usr/local/lib/node_modules/gulp-cli/node_modules/yargs/index.js:6:1) at Module._compile (internal/modules/cjs/loader.js:1147:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1167:10) at Module.load (internal/modules/cjs/loader.js:996:32) at Function.Module._load (internal/modules/cjs/loader.js:896:14) at Module.require (internal/modules/cjs/loader.js:1036:19) at require (internal/modules/cjs/helpers.js:72:18) { errno: -1, code: 'EPERM', syscall: 'uv_cwd' }
This seemed strange to me because I had just used the gulp
tool and everything was fine. Then I tried to use the bundle update
command, thinking that this can be a hint to localize the problem.
$ bundle update shell-init: error retrieving current directory: getcwd: cannot access parent directories: Operation not permitted Traceback (most recent call last): 9: from /usr/local/bin/bundle:23:in <main> 8: from /Library/Ruby/Site/2.6.0/rubygems.rb:294:in `activate_bin_path' 7: from /Library/Ruby/Site/2.6.0/rubygems.rb:264:in `find_spec_for_exe' 6: from /Library/Ruby/Site/2.6.0/rubygems/dependency.rb:284:in `matching_specs' 5: from /Library/Ruby/Site/2.6.0/rubygems/bundler_version_finder.rb:45:in `filter!' 4: from /Library/Ruby/Site/2.6.0/rubygems/bundler_version_finder.rb:7:in `bundler_version' 3: from /Library/Ruby/Site/2.6.0/rubygems/bundler_version_finder.rb:22:in `bundler_version_with_reason' 2: from /Library/Ruby/Site/2.6.0/rubygems/bundler_version_finder.rb:73:in `lockfile_version' 1: from /Library/Ruby/Site/2.6.0/rubygems/bundler_version_finder.rb:85:in `lockfile_contents' /Library/Ruby/Site/2.6.0/rubygems/bundler_version_finder.rb:85:in pwd': Operation not permitted - getcwd (Errno::EPERM)
The error appeared again, but now the error message is self explanatory. It saying that the shell-init
cannot access parent directories, and this is because error retrieving current directory
.
In my case, this makes sense because I used the Finder to delete my app project catalog and restore it from the backup after trying new things and changed my mind to keep them. Facepalm >_<
Now we know what caused this error.
How to solve it
Once we know what is causing the gulp
run to fail, we can use it to solve the problem. It is a really easy process. To solve this problem, we just need to re-enter into our app project directory. Now, step by step guide.
In the Terminal app, type the following command and press the Enter
key to go up one level in the directory.
Now, type the following command and press the Enter
key to navigate to your working directory (in this example the my_app_dir
catalog is used).
Important! In my case the working directory is the catalog of my app project called
my_app_dir
where the problem has occurred. Change the command above to suit your case.
Conclusion
That’s it, you’re done. Now the gulp
should run without the Error: EPERM: operation not permitted, uv_cwd
error. So simple isn’t it?
If you are having trouble fixing this problem with the instructions above, but are being able to solve this problem with any another method please describe it in the comment section below. Thanks!
I hope this article has helped you learn how to fix the Error: EPERM: operation not permitted, uv_cwd
error. If this article has helped you then please leave a comment
Thanks for reading!