Error spawn node enoent

[Solved-5 Solutions] Error spawn enoent on node.js Error Description: We get the following error: click below button to copy the code. By — nodejs tutorial — team Solution 1: click below button to copy the code. By — nodejs tutorial — team The problem of this error is, there is really little information in […]

Содержание

  1. [Solved-5 Solutions] Error spawn enoent on node.js
  2. Error Description:
  3. Solution 1:
  4. Solution 2:
  5. Solution 3:
  6. Identify the Event Emitter that emits the error event
  7. Solution 4:
  8. Ensure the environment variable $PATH is set
  9. Solution 5:
  10. Ensure command exists on a directory of those defined in PATH
  11. Related Searches to Error spawn enoent on node.js
  12. How to fix «Error: spawn node ENOENT» when using child_process in Node.js
  13. About the author
  14. Error: spawn «C:Program Filesnodejsnode.exe» ENOENT at notFoundError (C:UsersManeeshaAppDataRoamingnpmnode_modulesionicnode_modulescross-spawnlibenoent.js:11:11) #1092
  15. Comments
  16. Error: spawn ENOENT #277
  17. Comments
  18. Как отладить «Ошибка: вызвать ENOENT» на node.js?
  19. Когда я получаю следующую ошибку:
  20. Какую процедуру я могу выполнить, чтобы исправить ее?
  21. ОТВЕТЫ
  22. Ответ 1
  23. Ответ 2
  24. Шаг 1: Убедитесь, что spawn называется правильным способом
  25. Шаг 2: Идентифицируйте событие, излучающее событие ошибки
  26. Шаг 3. Убедитесь, что переменная среды $PATH установлена ​​
  27. Шаг 4: Убедитесь, что command существует в каталоге тех, которые определены в PATH
  28. Ответ 3
  29. Ответ 4
  30. Ответ 5
  31. Ответ 6
  32. Ответ 7
  33. Ответ 8
  34. Ответ 9
  35. Ответ 10
  36. Ответ 11
  37. Ответ 12
  38. Ответ 13
  39. Ответ 14
  40. Ответ 15
  41. Ответ 16
  42. Ответ 17
  43. Ответ 18
  44. Ответ 19
  45. Вы меняете опцию env ?
  46. Ответ 20
  47. Ответ 21
  48. Действия

[Solved-5 Solutions] Error spawn enoent on node.js

Error Description:

We get the following error:

click below button to copy the code. By — nodejs tutorial — team

Solution 1:

click below button to copy the code. By — nodejs tutorial — team

The problem of this error is, there is really little information in the error message to tell you where the call site is, i.e. which executable/command is not found, especially when you have a large code base where there are a lot of spawn calls.

  • The key idea is to wrap the original spawn call with a wrapper which prints the arguments send to the spawn call.
  • Here is the wrapper function, put it at the top of the index.js or whatever your server’s starting script.
click below button to copy the code. By — nodejs tutorial — team

Then the next time you run your application, before the uncaught exception’s message you will see something like that:

click below button to copy the code. By — nodejs tutorial — team

Solution 2:

Ensure spawn is called the right way

First, review the docs for child_process.spawn( command, args, options ):

Solution 3:

Identify the Event Emitter that emits the error event

  • Search on your source code for each call to spawn, or child_process.spawn
click below button to copy the code. By — nodejs tutorial — team

and attach there an event listener for the ‘error’ event, so you get noticed the exact Event Emitter that is throwing it as ‘Unhandled’. After debugging, that handler can be removed.

click below button to copy the code. By — nodejs tutorial — team

Execute and you should get the file path and line number where your ‘error’ listener was registered. Something like:

click below button to copy the code. By — nodejs tutorial — team
click below button to copy the code. By — nodejs tutorial — team

Solution 4:

Ensure the environment variable $PATH is set

There are two possible scenarios:

  • You rely on the default spawn behaviour, so child process environment will be the same as process.env.
  • You are explicity passing an env object to spawn on the options argument.

In both scenarios, you must inspect the PATH key on the environment object that the spawned child process will use.

Example for scenario 1

click below button to copy the code. By — nodejs tutorial — team

Example for scenario 2

click below button to copy the code. By — nodejs tutorial — team

The absence of PATH (i.e., it’s undefined) will cause spawn to emit the ENOENT error, as it will not be possible to locate any command unless it’s an absolute path to the executable file.

Solution 5:

Ensure command exists on a directory of those defined in PATH

Spawn may emit the ENOENT error if the filename command (i.e, ‘some-command’) does not exist in at least one of the directories defined on PATH.

Locate the exact place of command. On most linux distributions, this can be done from a terminal with the which command. It will tell you the absolute path to the executable file (like above), or tell if it’s not found.

Example usage of which and its output when a command is found

click below button to copy the code. By — nodejs tutorial — team

Example usage of which and its output when a command is not found

click below button to copy the code. By — nodejs tutorial — team
  • miss-installed programs are the most common cause for a not found command. Refer to each command documentation if needed and install it.
  • When command is a simple script file ensure it’s accessible from a directory on the PATH. If it’s not, either move it to one or make a link to it.
  • Once you determine PATH is correctly set and command is accessible from it, you should be able to spawn your child process without spawn ENOENT being thrown.

World’s No 1 Animated self learning Website with Informative tutorials explaining the code and the choices behind it all.

Источник

How to fix «Error: spawn node ENOENT» when using child_process in Node.js

Have you ever stumbled upon this error when using spawn from Node.js’ child_process module?

I keep running into this error over and over again. And what confuses me every time is that I could always swear that the given piece of code was working before.

It turns out that when you pass in options.env as the third argument to set an environment variable on the child process, the error appears:

To fix it, simply pass along the PATH environment variable from the parent process as well:

The reason the spawn was broken in the first place was because we were overriding the child process’ environment variables in options.env which it normally would have inherited from its parent process.

So without the PATH environment variable, the operating system doesn’t know where to look for the node executable.

I hope this helped!

Hi, I’m Max! I’m a fullstack JavaScript developer living in Berlin.

When I’m not working on one of my personal projects, writing blog posts or making YouTube videos, I help my clients bring their ideas to life as a freelance web developer.

If you need help on a project, please reach out and let’s work together.

To stay updated with new blog posts, follow me on Twitter or subscribe to my RSS feed.

Источник

Error: spawn «C:Program Filesnodejsnode.exe» ENOENT at notFoundError (C:UsersManeeshaAppDataRoamingnpmnode_modulesionicnode_modulescross-spawnlibenoent.js:11:11) #1092

  • Node.js Version:8.9.1
  • OS: Windows 10
  • Scope (install, code, runtime, meta, other?): Runtime Error
  • Module (and version) (if relevant):
  • Compiler:ionic serve

Error: spawn «C:Program Filesnodejsnode.exe» ENOENT
at notFoundError (C:UsersManeeshaAppDataRoamingnpmnode_modulesionicnode_modulescross-spawnlibenoent.js:11:11)
at verifyENOENT (C:UsersManeeshaAppDataRoamingnpmnode_modulesionicnode_modulescross-spawnlibenoent.js:46:16)
at ChildProcess.cp.emit (C:UsersManeeshaAppDataRoamingnpmnode_modulesionicnode_modulescross-spawnlibenoent.js:33:19)
at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)

The text was updated successfully, but these errors were encountered:

Same problem here

@bhekor this happen because of the internet connection. check the connection and type
ionic serve

Yes, but I need to be able to serve it offline.

I have the same problem

The call stack is an evidence of node binary in execution, but the spawn failure would indicate a possible issue with the options passed to the custom launcher — cross-spawn. So I don’t see any evidence of an issue with node, instead with the module(s). Looks like there are open issues reported against ionic, please track the progress there: ionic-team/ionic-cli#2866

You may please re-open if it turns out to be a node issue.

como puedo solucionar el mismo error. la version del node = 8.11.2

Источник

Error: spawn ENOENT #277

Node-gyp refuses to build any native modules I’ve tried. I’m on Windows 7 64 bit (I’m trying to compile for x86 though, as I don’t have the x64 SDK installed). Node-gyp says it’s a bug which I need to report, so here I am:

The text was updated successfully, but these errors were encountered:

Similar problem here, but Windows 8 and VS2012 installed. (sqlite3, ejdb, or any node-gyp library)

I too have the same error,please some one provide solution

Hi!
start the build with nodejs 0.8 — this will provide much more information about the error..

In my machine (I installed python manually later and I set PYTHON environment variable and python binary to the path) I removed the PYTHON variable from environment properties (set PYTHON=) and it’s work correctly.

i also have windows 7 64 bits, when i try to install pg module, i have the same error
Spawn ENOENT
error at errnoException (child_process.js:980:11)
error at Process.ChildProcess._handle.onexit (child_process.js:771:34)
System Windows_NT 6.1..7600
node -v v0.10.12
npm -v 1.2.32

aditional —-
node-gyp -v 0.10.5
Python 2.7.5 (64-bit)
Microsoft Visual Studio C++ 2010 (64-bit)
Windows 7 64-bit SDK
Microsoft Visual Studio C++ 2012 for Windows Desktop

scunish, start with nodejs 0.8 and you see the problem.

hi b0c1 thank you for your response, what do you mean by start with node 0.8 im sorry i didnt undestood well,
do you mean install node version 0.8? and run from there?

i downgraded the version of node now the error is different,

1716 error ref@0.1.3 install: node-gyp rebuild
1716 error cmd «/c» «node-gyp rebuild» failed with 127
1717 error Failed at the ref@0.1.3 install script.
1717 error This is most likely a problem with the ref package,
1717 error not with npm itself.
1717 error Tell the author that this fails on your system:
1717 error node-gyp rebuild
1717 error You can get their info via:
1717 error npm owner ls ref
1717 error There is likely additional logging output above.
1718 error System Windows_NT 6.1.7600
1719 error command «C:Program Filesnodejsnode.exe» «C:Program Filesnodejsnode_modulesnpmbinnpm-cli.js» «install» «pg»
1720 error cwd C:UsersDesarrolloDocumentsNode Code
1721 error node -v v0.8.22
1722 error npm -v 1.2.14
1723 error code ELIFECYCLE
1724 verbose exit [ 1, true ]

Nope. I mean install nodejs 0.8 🙂 You using: «node -v v0.10.12» 🙂
What I do:

  • I copied the whole directory to another name
  • download the 0.8 version from http://nodejs.org/dist/v0.8.25/ (node.exe, node.exp, node.lib, node.pdb) and put it to the original directory (replaced the files)
  • run your code again 🙂

hi b0c1 thank you once more, my last comment was by using version 0.8.22 and threw that error, i switched to v 0.8.25 as u suggested and the new error is.

npm ERR! werid error 127
npm http 304 https://registry.npmjs.org/rmdir
npm ERR! not ok code 0

funny to read weird error

Ehh, funny, but maybe you can create an issue with the new data

thank you b0c1 good luck.

I was getting the same problem. Solved defining the env variables:

Worked like charm

I tried setting the Python path, but that didn’t work.

Downgrading to Node v0.8.25 worked!
The command node-gyp configure succeeded.
However node-gyp build failed. I was still able to compile the project manually by opening the solution in Visual Studio, though.

Источник

Как отладить «Ошибка: вызвать ENOENT» на node.js?

Когда я получаю следующую ошибку:

Какую процедуру я могу выполнить, чтобы исправить ее?

Примечание автора.. Многие проблемы с этой ошибкой побудили меня опубликовать этот вопрос для будущих ссылок.

Связанные вопросы:

ОТВЕТЫ

Ответ 1

ПРИМЕЧАНИЕ. Эта ошибка почти всегда возникает из-за того, что команда не существует, потому что рабочий каталог не существует или из-за ошибки только для Windows.

Я нашел очень простой способ понять причину:

Проблема этой ошибки в том, что в сообщении об ошибке действительно мало информации, чтобы сказать вам, где находится сайт вызова, т.е. какой исполняемый файл/команда не найден, особенно если у вас большая кодовая база, где много вызовов спавна. С другой стороны, если мы знаем точную команду, которая вызывает ошибку, тогда мы можем следовать @laconbass ‘answer, чтобы решить проблему.

Я нашел очень простой способ определить, какая команда вызывает проблему, вместо добавления прослушивателей событий в вашем коде, как предложено в ответе @laconbass. Основная идея заключается в том, чтобы обернуть исходный вызов spawn оболочкой, которая печатает аргументы, отправленные на вызов spawn.

Вот функция-обертка, поместите ее в верхнюю часть index.js или любого другого сценария запуска вашего сервера.

Затем в следующий раз, когда вы запустите свое приложение, перед сообщением с неперехваченным исключением вы увидите что-то вроде этого:

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

Ответ 2

Шаг 1: Убедитесь, что spawn называется правильным способом

Запускает новый процесс с заданным command с аргументами командной строки в args . Если опустить, args по умолчанию задает пустой массив.

Третий аргумент используется для указания дополнительных параметров, по умолчанию:

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

Убедитесь, что вы не вставляете аргументы командной строки в command , а весь spawn вызов действителен. Перейдите к следующему шагу.

Шаг 2: Идентифицируйте событие, излучающее событие ошибки

Найдите исходный код для каждого вызова spawn или child_process.spawn , т.е.

и прикрепите там прослушиватель событий для события «error», чтобы вы заметили точный Event Emitter, который бросает его как «Unhandled». После отладки этот обработчик можно удалить.

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

Если первые две строки все еще

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

Шаг 3. Убедитесь, что переменная среды $PATH установлена ​​

Возможны два сценария:

  • Вы полагаетесь на поведение по умолчанию spawn , поэтому дочерняя среда процесса будет такой же, как process.env .
  • Вы — экспликация, передающая объект env на spawn в аргументе options .

В обоих сценариях вы должны проверить ключ PATH на объекте среды, который будет использовать дочерний процесс, созданный.

Пример сценария 1

Пример сценария 2

Отсутствие PATH (т.е. it undefined ) приведет к тому, что spawn испустит ошибку ENOENT , так как не удастся найти какой-либо command , если только это абсолютный путь к исполняемому файлу.

Когда PATH установлен правильно, перейдите к следующему шагу. Это должен быть каталог или список каталогов. Последний случай является обычным.

Шаг 4: Убедитесь, что command существует в каталоге тех, которые определены в PATH

Spawn может испускать ошибку ENOENT , если имя файла command (т.е. ‘some-command’) не существует, по крайней мере, в одном из каталогов, определенных в PATH .

Найдите точное место command . В большинстве дистрибутивов Linux это можно сделать с терминала с помощью команды which . Он укажет вам абсолютный путь к исполняемому файлу (например, выше) или сообщите, не найден ли он.

Пример использования которого и его вывод, когда команда найдена

Пример использования которого и его вывод, когда команда не найдена

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

Когда команда представляет собой простой файл script, убедитесь, что он доступен из каталога в PATH .. Если это не так, переместите его на один или создайте для него ссылку.

После того, как вы определили PATH правильно установленный и command доступен из него, вы сможете запустить дочерний процесс без spawn ENOENT .

Ответ 3

Как @DanielImfeld указал на него, ENOENT будет выброшен, если вы укажете «cwd» в параметрах, но данный каталог не существует.

Ответ 4

Решение для Windows: замените spawn на node-cross-spawn. Например, например, в начале вашего app.js:

Ответ 5

Ответ @laconbass помог мне и, вероятно, является наиболее правильным.

Я пришел сюда, потому что я использовал спавн неправильно. В качестве простого примера:

это правильно:

Тем не менее, я рекомендую сделать это следующим образом:

это потому, что тогда cp.on(‘exit’, fn) будет всегда cp.on(‘exit’, fn) , пока bash установлен, в противном случае cp.on(‘error’, fn) может cp.on(‘error’, fn) первым, если мы используем его Первый способ, если мы запустим ‘npm’ напрямую.

Ответ 6

например. замените spawn (‘npm’, [‘-v’], ) с помощью:

для всех node.js версия:

для node.js 5.x и более поздних версий:

Ответ 7

Для всех, кто может наткнуться на это, если все остальные ответы не помогут, и вы находитесь в Windows, знайте, что в настоящее время существует большая проблема с spawn в Windows и переменную среды PATHEXT , которая может привести к тому, что определенные вызовы на запуск не будут работать в зависимости от того, как установлена ​​целевая команда.

Ответ 8

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

В частности, у меня есть приложение NodeJS, которое использует ImageMagick. Несмотря на то, что установлен пакет npm, ядро ​​Linux ImageMagick не было установлено. Я сделал apt-get для установки ImageMagick, и после этого все отлично поработало!

Ответ 9

Я столкнулся с той же проблемой, но нашел простой способ ее исправить. По-видимому, это ошибки spawn() , если программа была добавлена ​​в PATH пользователем (например, работают обычные системные команды).

Чтобы исправить это, вы можете использовать модуль which ( npm install —save which ):

Ответ 10

Убедитесь, что установленный модуль установлен или полный путь к команде, если он не является модулем node

Ответ 11

Используйте require(‘child_process’).exec вместо spawn для более конкретного сообщения об ошибке!

Ответ 12

Я также проходил через эту досадную проблему, выполняя свои тестовые случаи, поэтому я попробовал много способов решить эту проблему. Но способ для меня — запустить ваш тестовый прогон из каталога, в котором находится ваш основной файл, который включает в себя функцию spawn для nodejs, примерно так:

Например, это имя файла test.js, поэтому просто перейдите в папку, в которой он находится. В моем случае это тестовая папка:

тогда от запуска вашего тестового бегуна в моем случае его мокко, так что это будет так:

Я потратил больше одного дня, чтобы понять это. Наслаждаться!!

Ответ 13

Я получал эту ошибку при попытке отладки программы node.js из редактора VS Code в системе Debian Linux. Я заметил, что в Windows все работает нормально. Решения, приведенные здесь ранее, не помогли, потому что я не написал никаких команд «икры». Оскорбительный код предположительно был написан Microsoft и скрыт под капотом программы VS Code.

Далее я заметил, что node.js называется node в Windows, но на Debian (и, предположительно, в системах на основе Debian, таких как Ubuntu), он называется nodejs. Поэтому я создал псевдоним — с корневого терминала, я побежал

и это решило проблему. Такая же или аналогичная процедура, по-видимому, будет работать в других случаях, когда ваш node.js называется nodejs, но вы запускаете программу, которая ожидает, что она будет называться node, или наоборот.

Ответ 14

У меня такая же ошибка для Windows 8. Проблема в том, что отсутствует переменная среды вашего системного пути. Добавьте значение «C:WindowsSystem32 » в переменную PATH вашей системы.

Ответ 15

Если вы работаете в Windows Node.js делает некоторые смешные дела при обработке котировок, которые могут привести к выдаче команды, которая, как вам известно, работает с консоли, но не выполняется при Node. Например, следующее должно работать:

но терпит неудачу. Там есть фантастически недокументированная опция windowsVerbatimArguments для обработки кавычек/подобных, которые, похоже, делают трюк, просто добавьте следующее к вашему объекту opts:

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

Ответ 16

решение в моем случае

Ответ 17

npm install -g nodemon помог мне

Ответ 18

Я столкнулся с этой проблемой в Windows, где вызовы exec и spawn с одной и той же командой (без аргументов) работали нормально для exec (поэтому я знал, что моя команда была на $PATH ), но spawn будет дать ENOENT. Оказалось, что мне просто нужно добавить .exe к команде, которую я использовал:

Ответ 19

Вы меняете опцию env ?

Тогда посмотрите на этот ответ.

Я пытался порождать процесс узла и TIL, чтобы вы распространяли существующие переменные окружения при порождении, иначе вы потеряете переменную окружения PATH и, возможно, другие важные.

Это было исправление для меня:

Ответ 20

Если у вас возникла эта проблема с приложением, источник которого вы не можете изменить, подумайте о его вызове с переменной среды NODE_DEBUG , установленной в child_process , например, NODE_DEBUG=child_process yarn test . Это предоставит вам информацию о том, какие командные строки были вызваны в каком каталоге и, как правило, последняя деталь является причиной сбоя.

Ответ 21

Добавьте C:WindowsSystem32 в переменную среды path .

Действия

Перейдите на мой компьютер и свойства

Нажмите «Дополнительные настройки»

Затем в переменных среды

Выберите path , а затем нажмите на ссылку

Вставьте следующие, если они еще не присутствуют: C:WindowsSystem32

Закройте командную строку

Запустите команду, которую вы хотите запустить

Источник

Error Description:

We get the following error:

events.js:72
throw er; // Unhandled 'error' event
              ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34) 
click below button to copy the code. By — nodejs tutorial — team

Solution 1:

Error: spawn ENOENT 
click below button to copy the code. By — nodejs tutorial — team

The problem of this error is, there is really little information in the error message to tell you where the call site is, i.e. which executable/command is not found, especially when you have a large code base where there are a lot of spawn calls.

  • The key idea is to wrap the original spawn call with a wrapper which prints the arguments send to the spawn call.
  • Here is the wrapper function, put it at the top of the index.js or whatever your server’s starting script.
(function(){
var childProcess = require("child_process");
var oldSpawn = childProcess.spawn;
function mySpawn(){
        console.log('spawn called');
        console.log(arguments);
var result = oldSpawn.apply(this, arguments);
return result;
}
    childProcess.spawn = mySpawn;
})(); 
click below button to copy the code. By — nodejs tutorial — team

Then the next time you run your application, before the uncaught exception’s message you will see something like that:

spawn called
{'0':'hg',
'1':[],
'2':
{ cwd:'/* omitted */',
     env:{ IP:'0.0.0.0'},
     args:[]}} 
click below button to copy the code. By — nodejs tutorial — team

Solution 2:

Ensure spawn is called the right way

First, review the docs for child_process.spawn( command, args, options ):

«Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.
The third argument is used to specify additional options, which defaults to:
{ cwd: undefined, env: process.env }
Use env to specify environment variables that will be visible to the new process, the default is process.env.
«

Solution 3:

Identify the Event Emitter that emits the error event

  • Search on your source code for each call to spawn, or child_process.spawn
spawn('some-command',['--help']);
 
click below button to copy the code. By — nodejs tutorial — team

and attach there an event listener for the ‘error’ event, so you get noticed the exact Event Emitter that is throwing it as ‘Unhandled’. After debugging, that handler can be removed.

spawn('some-command',['--help'])
.on('error',function( err ){throw err })
; 
click below button to copy the code. By — nodejs tutorial — team

Execute and you should get the file path and line number where your ‘error’ listener was registered. Something like:

/file/that/registers/the/error/listener.js:29
      throw err;
            ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34) 
click below button to copy the code. By — nodejs tutorial — team
events.js:72
        throw er; // Unhandled 'error' event 
click below button to copy the code. By — nodejs tutorial — team

Solution 4:

Ensure the environment variable $PATH is set

There are two possible scenarios:

  • You rely on the default spawn behaviour, so child process environment will be the same as process.env.
  • You are explicity passing an env object to spawn on the options argument.

In both scenarios, you must inspect the PATH key on the environment object that the spawned child process will use.

Example for scenario 1

// inspect the PATH key on process.env
console.log( process.env.PATH );
spawn('some-command',['--help']); 
click below button to copy the code. By — nodejs tutorial — team

Example for scenario 2

var env = getEnvKeyValuePairsSomeHow();
// inspect the PATH key on the env object
console.log( env.PATH );
spawn('some-command',['--help'],{ env: env }); 
click below button to copy the code. By — nodejs tutorial — team

The absence of PATH (i.e., it’s undefined) will cause spawn to emit the ENOENT error, as it will not be possible to locate any command unless it’s an absolute path to the executable file.

Solution 5:

Ensure command exists on a directory of those defined in PATH

Spawn may emit the ENOENT error if the filename command (i.e, ‘some-command’) does not exist in at least one of the directories defined on PATH.

Locate the exact place of command. On most linux distributions, this can be done from a terminal with the which command. It will tell you the absolute path to the executable file (like above), or tell if it’s not found.

Example usage of which and its output when a command is found

> which some-command
some-command is /usr/bin/some-command 
click below button to copy the code. By — nodejs tutorial — team

Example usage of which and its output when a command is not found

> which some-command
bash: type: some-command: not found 
click below button to copy the code. By — nodejs tutorial — team
  • miss-installed programs are the most common cause for a not found command. Refer to each command documentation if needed and install it.
  • When command is a simple script file ensure it’s accessible from a directory on the PATH. If it’s not, either move it to one or make a link to it.
  • Once you determine PATH is correctly set and command is accessible from it, you should be able to spawn your child process without spawn ENOENT being thrown.

New issue

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

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

Already on GitHub?
Sign in
to your account


Closed

atubo2012 opened this issue

May 7, 2018

· 5 comments

Comments

@atubo2012

Your issue may already be reported!
Please search on the issue tracker before creating one.

What’s going wrong?

When I start up using following command, there are some errors in pm2.log :
pm2 start process.json
=====errors in pm2.log===============
[2018-05-07 16:21:11] PM2 error: Error: spawn node ENOENT
at exports._errnoException (util.js:1018:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
at onErrorNT (internal/child_process.js:367:16)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)

How could we reproduce this issue?

Supporting information

Please run the following command (available on PM2 >= 2.6)

— PM2 REPORT (Mon May 07 2018 16:40:27 GMT+0800 (中国标准时间)) ——————-

— Daemon ————————————————-
pm2d version : 2.10.3
node version : 6.11.0
node path : undefined
argv : C:Program Filesnodejsnode.exe,C:Usersx1AppDataRoamingnpmnode_modulespm2libDaemon.js
argv0 : node
user : undefined
uid : N/A
gid : N/A
uptime : 5min

— CLI —————————————————-
local pm2 : 2.10.3
node version : 6.11.0
node path : undefined
argv : C:Program Filesnodejsnode.exe,C:Usersx1AppDataRoamingnpmnode_modulespm2binpm2,report
argv0 : node
user : x1

— System info ———————————————
arch : x64
platform : win32
type : Windows_NT
cpus : Intel(R) Core(TM) i5-6200U CPU @ 2.30GHz
cpus nb : 4
freemem : 3017281536
totalmem : 8419135488
home : C:Usersx1

— PM2 list ————————————————
┌──────────┬────┬──────┬─────┬─────────┬─────────┬────────┬─────┬────────┬──────┬──────────┐
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
├──────────┼────┼──────┼─────┼─────────┼─────────┼────────┼─────┼────────┼──────┼──────────┤
│ zhaogong │ 0 │ fork │ N/A │ errored │ 0 │ 0 │ 0% │ 0 B │ x1 │ enabled │
└──────────┴────┴──────┴─────┴─────────┴─────────┴────────┴─────┴────────┴──────┴──────────┘

— Daemon logs ———————————————
C:Usersx1.pm2pm2.log last 20 lines:
PM2 | [2018-05-07 16:34:46] PM2 log: Node.js version : 6.11.0
PM2 | [2018-05-07 16:34:46] PM2 log: Current arch : x64
PM2 | [2018-05-07 16:34:46] PM2 log: PM2 home : C:Usersx1.pm2
PM2 | [2018-05-07 16:34:46] PM2 log: PM2 PID file : C:Usersx1.pm2pm2.pid
PM2 | [2018-05-07 16:34:46] PM2 log: RPC socket file : .piperpc.sock
PM2 | [2018-05-07 16:34:46] PM2 log: BUS socket file : .pipepub.sock
PM2 | [2018-05-07 16:34:46] PM2 log: Application log path : C:Usersx1.pm2logs
PM2 | [2018-05-07 16:34:46] PM2 log: Process dump file : C:Usersx1.pm2dump.pm2
PM2 | [2018-05-07 16:34:46] PM2 log: Concurrent actions : 2
PM2 | [2018-05-07 16:34:46] PM2 log: SIGTERM timeout : 1600
PM2 | [2018-05-07 16:34:46] PM2 log: ===============================================================================
PM2 | [2018-05-07 16:34:46] PM2 log: [Watch] Start watching zhaogong
PM2 | [2018-05-07 16:34:46] PM2 log: Starting execution sequence in -fork mode- for app name:zhaogong id:0
PM2 | [2018-05-07 16:34:46] PM2 log: App name:zhaogong id:0 online
PM2 | [2018-05-07 16:34:46] PM2 error: Error: spawn node ENOENT
PM2 | at exports._errnoException (util.js:1018:11)
PM2 | at Process.ChildProcess._handle.onexit (internal/child_process.js:193:32)
PM2 | at onErrorNT (internal/child_process.js:367:16)
PM2 | at _combinedTickCallback (internal/process/next_tick.js:80:11)
PM2 | at process._tickDomainCallback (internal/process/next_tick.js:128:9)

@Unitech

how did you installed nodejs?

@atubo2012

Solved after I changed the path in the process.json from «cwd»: «/root/dev/zhaogong-be» to «cwd»: «d:/zhaogong-be».

@alsotang

I also meet this error message, and I solved it.

I use pm2 startup to init my services when the vps restart, and pm2 can not start my nodejs program with this error message.

After I inspect my environment, I find that I install nodejs through fnm(https://github.com/Schniz/fnm). My nodejs program is not in the system’s original $PATH but a custom place. So maybe the start time of fnm is later than pm2.

Instead, I install nodejs from apt.

from https://github.com/nodesource/distributions/blob/master/README.md

# Using Ubuntu
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

# Using Debian, as root
curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
apt-get install -y nodejs

@OmsinKrissada

Changing from fnm to system’s node works perfectly. Though, it seems like the problem is with fnm creating a new random bin path on boot. PM2 saves the path in which node is located, so when PM2 tries to call node on the old path it just doesn’t exist.

Which makes me wonder if it’s possible to configure fnm to use a persistent path, or tell pm2 to re-read PATH variable after reboot or not saving the PATH at all.

@axi

Found this while searching «PM2 error: Error: spawn node ENOENT» and it helped me figuring out that was a nodejs version issue. I wasn’t using correct version, had to use:

pm2 start server.js --interpreter=/home/ubuntu/.nvm/versions/node/v16.13.2/bin/node

In case it can help someone someday :-)

NOTE: This error is almost always caused because the command does not exist, because the working directory does not exist, or from a windows-only bug.

I found a particular easy way to get the idea of the root cause of:

Error: spawn ENOENT

The problem of this error is, there is really little information in the error message to tell you where the call site is, i.e. which executable/command is not found, especially when you have a large code base where there are a lot of spawn calls. On the other hand, if we know the exact command that cause the error then we can follow @laconbass’ answer to fix the problem.

I found a very easy way to spot which command cause the problem rather than adding event listeners everywhere in your code as suggested in @laconbass’ answer. The key idea is to wrap the original spawn call with a wrapper which prints the arguments send to the spawn call.

Here is the wrapper function, put it at the top of the index.js or whatever your server’s starting script.

(function() {
    var childProcess = require("child_process");
    var oldSpawn = childProcess.spawn;
    function mySpawn() {
        console.log('spawn called');
        console.log(arguments);
        var result = oldSpawn.apply(this, arguments);
        return result;
    }
    childProcess.spawn = mySpawn;
})();

Then the next time you run your application, before the uncaught exception’s message you will see something like that:

spawn called
{ '0': 'hg',
  '1': [],
  '2':
   { cwd: '/* omitted */',
     env: { IP: '0.0.0.0' },
     args: [] } }

In this way you can easily know which command actually is executed and then you can find out why nodejs cannot find the executable to fix the problem.

Step 1: Ensure spawn is called the right way

First, review the docs for child_process.spawn( command, args, options ):

Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.

The third argument is used to specify additional options, which defaults to:

{ cwd: undefined, env: process.env }

Use env to specify environment variables that will be visible to the new process, the default is process.env.

Ensure you are not putting any command line arguments in command and the whole spawn call is valid. Proceed to next step.

Step 2: Identify the Event Emitter that emits the error event

Search on your source code for each call to spawn, or child_process.spawn, i.e.

spawn('some-command', [ '--help' ]);

and attach there an event listener for the ‘error’ event, so you get noticed the exact Event Emitter that is throwing it as ‘Unhandled’. After debugging, that handler can be removed.

spawn('some-command', [ '--help' ])
  .on('error', function( err ){ throw err })
;

Execute and you should get the file path and line number where your ‘error’ listener was registered. Something like:

/file/that/registers/the/error/listener.js:29
      throw err;
            ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

If the first two lines are still

events.js:72
        throw er; // Unhandled 'error' event

do this step again until they are not. You must identify the listener that emits the error before going on next step.

Step 3: Ensure the environment variable $PATH is set

There are two possible scenarios:

  1. You rely on the default spawn behaviour, so child process environment will be the same as process.env.
  2. You are explicity passing an env object to spawn on the options argument.

In both scenarios, you must inspect the PATH key on the environment object that the spawned child process will use.

Example for scenario 1

// inspect the PATH key on process.env
console.log( process.env.PATH );
spawn('some-command', ['--help']);

Example for scenario 2

var env = getEnvKeyValuePairsSomeHow();
// inspect the PATH key on the env object
console.log( env.PATH );
spawn('some-command', ['--help'], { env: env });

The absence of PATH (i.e., it’s undefined) will cause spawn to emit the ENOENT error, as it will not be possible to locate any command unless it’s an absolute path to the executable file.

When PATH is correctly set, proceed to next step. It should be a directory, or a list of directories. Last case is the usual.

Step 4: Ensure command exists on a directory of those defined in PATH

Spawn may emit the ENOENT error if the filename command (i.e, ‘some-command’) does not exist in at least one of the directories defined on PATH.

Locate the exact place of command. On most linux distributions, this can be done from a terminal with the which command. It will tell you the absolute path to the executable file (like above), or tell if it’s not found.

Example usage of which and its output when a command is found

> which some-command
some-command is /usr/bin/some-command

Example usage of which and its output when a command is not found

> which some-command
bash: type: some-command: not found

miss-installed programs are the most common cause for a not found command. Refer to each command documentation if needed and install it.

When command is a simple script file ensure it’s accessible from a directory on the PATH. If it’s not, either move it to one or make a link to it.

Once you determine PATH is correctly set and command is accessible from it, you should be able to spawn your child process without spawn ENOENT being thrown.

Шаг 1: Убедитесь, что spawn называется правильным способом

Сначала просмотрите docs для child_process.spawn(команда, args, options):

Запускает новый процесс с заданным command с аргументами командной строки в args. Если опустить, args по умолчанию задает пустой массив.

Третий аргумент используется для указания дополнительных параметров, по умолчанию:

{ cwd: undefined, env: process.env }

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

Убедитесь, что вы не вставляете аргументы командной строки в command, а весь spawn вызов действителен. Перейдите к следующему шагу.

Шаг 2: Идентифицируйте событие, излучающее событие ошибки

Найдите исходный код для каждого вызова spawn или child_process.spawn, т.е.

spawn('some-command', [ '--help' ]);

и прикрепите там прослушиватель событий для события «error», чтобы вы заметили точный Event Emitter, который бросает его как «Unhandled». После отладки этот обработчик можно удалить.

spawn('some-command', [ '--help' ])
  .on('error', function( err ){ throw err })
;

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

/file/that/registers/the/error/listener.js:29
      throw err;
            ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

Если первые две строки все еще

events.js:72
        throw er; // Unhandled 'error' event

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

Шаг 3. Убедитесь, что переменная среды $PATH установлена ​​

Возможны два сценария:

  • Вы полагаетесь на поведение по умолчанию spawn, поэтому дочерняя среда процесса будет такой же, как process.env.
  • Вы — экспликация, передающая объект env на spawn в аргументе options.

В обоих сценариях вы должны проверить ключ PATH на объекте среды, который будет использовать дочерний процесс, созданный.

Пример сценария 1

// inspect the PATH key on process.env
console.log( process.env.PATH );
spawn('some-command', ['--help']);

Пример сценария 2

var env = getEnvKeyValuePairsSomeHow();
// inspect the PATH key on the env object
console.log( env.PATH );
spawn('some-command', ['--help'], { env: env });

Отсутствие PATH (т.е. it undefined) приведет к тому, что spawn испустит ошибку ENOENT, так как не удастся найти какой-либо command, если только это абсолютный путь к исполняемому файлу.

Когда PATH установлен правильно, перейдите к следующему шагу. Это должен быть каталог или список каталогов. Последний случай является обычным.

Шаг 4: Убедитесь, что command существует в каталоге тех, которые определены в PATH

Spawn может испускать ошибку ENOENT, если имя файла command (т.е. ‘some-command’) не существует, по крайней мере, в одном из каталогов, определенных в PATH.

Найдите точное место command. В большинстве дистрибутивов Linux это можно сделать с терминала с помощью команды which. Он укажет вам абсолютный путь к исполняемому файлу (например, выше) или сообщите, не найден ли он.

Пример использования которого и его вывод, когда команда найдена

> which some-command
some-command is /usr/bin/some-command

Пример использования которого и его вывод, когда команда не найдена

> which some-command
bash: type: some-command: not found

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

Когда команда представляет собой простой файл script, убедитесь, что он доступен из каталога в PATH.. Если это не так, переместите его на один или создайте для него ссылку.

После того, как вы определили PATH правильно установленный и command доступен из него, вы сможете запустить дочерний процесс без spawn ENOENT.

4b9b3361

Ответ 1

ПРИМЕЧАНИЕ. Эта ошибка почти всегда возникает из-за того, что команда не существует, потому что рабочий каталог не существует или из-за ошибки только для Windows.

Я нашел очень простой способ понять причину:

Error: spawn ENOENT

Проблема этой ошибки в том, что в сообщении об ошибке действительно мало информации, чтобы сказать вам, где находится сайт вызова, т.е. какой исполняемый файл/команда не найден, особенно если у вас большая кодовая база, где много вызовов спавна. С другой стороны, если мы знаем точную команду, которая вызывает ошибку, тогда мы можем следовать @laconbass ‘answer, чтобы решить проблему.

Я нашел очень простой способ определить, какая команда вызывает проблему, вместо добавления прослушивателей событий в вашем коде, как предложено в ответе @laconbass. Основная идея заключается в том, чтобы обернуть исходный вызов spawn оболочкой, которая печатает аргументы, отправленные на вызов spawn.

Вот функция-обертка, поместите ее в верхнюю часть index.js или любого другого сценария запуска вашего сервера.

(function() {
    var childProcess = require("child_process");
    var oldSpawn = childProcess.spawn;
    function mySpawn() {
        console.log('spawn called');
        console.log(arguments);
        var result = oldSpawn.apply(this, arguments);
        return result;
    }
    childProcess.spawn = mySpawn;
})();

Затем в следующий раз, когда вы запустите свое приложение, перед сообщением с неперехваченным исключением вы увидите что-то вроде этого:

spawn called
{ '0': 'hg',
  '1': [],
  '2':
   { cwd: '/* omitted */',
     env: { IP: '0.0.0.0' },
     args: [] } }

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

Ответ 2

Шаг 1: Убедитесь, что spawn называется правильным способом

Сначала просмотрите docs для child_process.spawn(команда, args, options):

Запускает новый процесс с заданным command с аргументами командной строки в args. Если опустить, args по умолчанию задает пустой массив.

Третий аргумент используется для указания дополнительных параметров, по умолчанию:

{ cwd: undefined, env: process.env }

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

Убедитесь, что вы не вставляете аргументы командной строки в command, а весь spawn вызов действителен. Перейдите к следующему шагу.

Шаг 2: Идентифицируйте событие, излучающее событие ошибки

Найдите исходный код для каждого вызова spawn или child_process.spawn, т.е.

spawn('some-command', [ '--help' ]);

и прикрепите там прослушиватель событий для события «error», чтобы вы заметили точный Event Emitter, который бросает его как «Unhandled». После отладки этот обработчик можно удалить.

spawn('some-command', [ '--help' ])
  .on('error', function( err ){ throw err })
;

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

/file/that/registers/the/error/listener.js:29
      throw err;
            ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

Если первые две строки все еще

events.js:72
        throw er; // Unhandled 'error' event

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

Шаг 3. Убедитесь, что переменная среды $PATH установлена ​​

Возможны два сценария:

  • Вы полагаетесь на поведение по умолчанию spawn, поэтому дочерняя среда процесса будет такой же, как process.env.
  • Вы — экспликация, передающая объект env на spawn в аргументе options.

В обоих сценариях вы должны проверить ключ PATH на объекте среды, который будет использовать дочерний процесс, созданный.

Пример сценария 1

// inspect the PATH key on process.env
console.log( process.env.PATH );
spawn('some-command', ['--help']);

Пример сценария 2

var env = getEnvKeyValuePairsSomeHow();
// inspect the PATH key on the env object
console.log( env.PATH );
spawn('some-command', ['--help'], { env: env });

Отсутствие PATH (т.е. it undefined) приведет к тому, что spawn испустит ошибку ENOENT, так как не удастся найти какой-либо command, если только это абсолютный путь к исполняемому файлу.

Когда PATH установлен правильно, перейдите к следующему шагу. Это должен быть каталог или список каталогов. Последний случай является обычным.

Шаг 4: Убедитесь, что command существует в каталоге тех, которые определены в PATH

Spawn может испускать ошибку ENOENT, если имя файла command (т.е. ‘some-command’) не существует, по крайней мере, в одном из каталогов, определенных в PATH.

Найдите точное место command. В большинстве дистрибутивов Linux это можно сделать с терминала с помощью команды which. Он укажет вам абсолютный путь к исполняемому файлу (например, выше) или сообщите, не найден ли он.

Пример использования которого и его вывод, когда команда найдена

> which some-command
some-command is /usr/bin/some-command

Пример использования которого и его вывод, когда команда не найдена

> which some-command
bash: type: some-command: not found

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

Когда команда представляет собой простой файл script, убедитесь, что он доступен из каталога в PATH.. Если это не так, переместите его на один или создайте для него ссылку.

После того, как вы определили PATH правильно установленный и command доступен из него, вы сможете запустить дочерний процесс без spawn ENOENT.

Ответ 3

Как @DanielImfeld указал на него, ENOENT будет выброшен, если вы укажете «cwd» в параметрах, но данный каталог не существует.

Ответ 4

Решение для Windows: замените spawn на node-cross-spawn. Например, например, в начале вашего app.js:

(function() {
    var childProcess = require("child_process");
    childProcess.spawn = require('cross-spawn');
})(); 

Ответ 5

Ответ @laconbass помог мне и, вероятно, является наиболее правильным.

Я пришел сюда, потому что я использовал спавн неправильно. В качестве простого примера:

это неверно:

const s = cp.spawn('npm install -D suman', [], {
    cwd: root
});

это неверно:

const s = cp.spawn('npm', ['install -D suman'], {
    cwd: root
});

это правильно:

const s = cp.spawn('npm', ['install','-D','suman'], {
    cwd: root
});

Тем не менее, я рекомендую сделать это следующим образом:

const s = cp.spawn('bash');
s.stdin.end('cd "${root}" && npm install -D suman');
s.once('exit', code => {
   // exit
});

это потому, что тогда cp.on('exit', fn) будет всегда cp.on('exit', fn), пока bash установлен, в противном случае cp.on('error', fn) может cp.on('error', fn) первым, если мы используем его Первый способ, если мы запустим ‘npm’ напрямую.

Ответ 6

Для ENOENT в Windows https://github.com/nodejs/node-v0.x-archive/issues/2318#issuecomment-249355505 исправить.

например. замените spawn (‘npm’, [‘-v’], {stdio: ‘inherit’}) с помощью:

  • для всех node.js версия:

    spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['-v'], {stdio: 'inherit'})
    
  • для node.js 5.x и более поздних версий:

    spawn('npm', ['-v'], {stdio: 'inherit', shell: true})
    

Ответ 7

Для всех, кто может наткнуться на это, если все остальные ответы не помогут, и вы находитесь в Windows, знайте, что в настоящее время существует большая проблема с spawn в Windows и переменную среды PATHEXT, которая может привести к тому, что определенные вызовы на запуск не будут работать в зависимости от того, как установлена ​​целевая команда.

Ответ 8

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

В частности, у меня есть приложение NodeJS, которое использует ImageMagick. Несмотря на то, что установлен пакет npm, ядро ​​Linux ImageMagick не было установлено. Я сделал apt-get для установки ImageMagick, и после этого все отлично поработало!

Ответ 9

Я столкнулся с той же проблемой, но нашел простой способ ее исправить.
По-видимому, это ошибки spawn(), если программа была добавлена ​​в PATH пользователем (например, работают обычные системные команды).

Чтобы исправить это, вы можете использовать модуль which (npm install --save which):

// Require which and child_process
const which = require('which');
const spawn = require('child_process').spawn;
// Find npm in PATH
const npm = which.sync('npm');
// Execute
const noErrorSpawn = spawn(npm, ['install']);

Ответ 10

Убедитесь, что установленный модуль установлен или полный путь к команде, если он не является модулем node

Ответ 11

Используйте require('child_process').exec вместо spawn для более конкретного сообщения об ошибке!

например:

var exec = require('child_process').exec;
var commandStr = 'java -jar something.jar';

exec(commandStr, function(error, stdout, stderr) {
  if(error || stderr) console.log(error || stderr);
  else console.log(stdout);
});

Ответ 12

Я также проходил через эту досадную проблему, выполняя свои тестовые случаи, поэтому я попробовал много способов решить эту проблему. Но способ для меня — запустить ваш тестовый прогон из каталога, в котором находится ваш основной файл, который включает в себя функцию spawn для nodejs, примерно так:

nodeProcess = spawn('node',params, {cwd: '../../node/', detached: true });

Например, это имя файла test.js, поэтому просто перейдите в папку, в которой он находится. В моем случае это тестовая папка:

cd root/test/

тогда от запуска вашего тестового бегуна в моем случае его мокко, так что это будет так:

mocha test.js

Я потратил больше одного дня, чтобы понять это. Наслаждаться!!

Ответ 13

Я получал эту ошибку при попытке отладки программы node.js из редактора VS Code в системе Debian Linux. Я заметил, что в Windows все работает нормально. Решения, приведенные здесь ранее, не помогли, потому что я не написал никаких команд «икры». Оскорбительный код предположительно был написан Microsoft и скрыт под капотом программы VS Code.

Далее я заметил, что node.js называется node в Windows, но на Debian (и, предположительно, в системах на основе Debian, таких как Ubuntu), он называется nodejs. Поэтому я создал псевдоним — с корневого терминала, я побежал

ln -s/usr/bin/nodejs/usr/local/bin/node

и это решило проблему. Такая же или аналогичная процедура, по-видимому, будет работать в других случаях, когда ваш node.js называется nodejs, но вы запускаете программу, которая ожидает, что она будет называться node, или наоборот.

Ответ 14

У меня такая же ошибка для Windows 8. Проблема в том, что отсутствует переменная среды вашего системного пути. Добавьте значение «C:WindowsSystem32 » в переменную PATH вашей системы.

Ответ 15

Если вы работаете в Windows Node.js делает некоторые смешные дела при обработке котировок, которые могут привести к выдаче команды, которая, как вам известно, работает с консоли, но не выполняется при Node. Например, следующее должно работать:

spawn('ping', ['"8.8.8.8"'], {});

но терпит неудачу. Там есть фантастически недокументированная опция windowsVerbatimArguments для обработки кавычек/подобных, которые, похоже, делают трюк, просто добавьте следующее к вашему объекту opts:

const opts = {
    windowsVerbatimArguments: true
};

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

 spawn('ping', ['"8.8.8.8"'], { windowsVerbatimArguments: true });

Ответ 16

решение в моем случае

var spawn = require('child_process').spawn;

const isWindows = /^win/.test(process.platform); 

spawn(isWindows ? 'twitter-proxy.cmd' : 'twitter-proxy');
spawn(isWindows ? 'http-server.cmd' : 'http-server');

Ответ 17

npm install -g nodemon помог мне

Ответ 18

Я столкнулся с этой проблемой в Windows, где вызовы exec и spawn с одной и той же командой (без аргументов) работали нормально для exec (поэтому я знал, что моя команда была на $PATH), но spawn будет дать ENOENT. Оказалось, что мне просто нужно добавить .exe к команде, которую я использовал:

import { exec, spawn } from 'child_process';

// This works fine
exec('p4 changes -s submitted');

// This gives the ENOENT error
spawn('p4');

// But this resolves it
spawn('p4.exe');
// Even works with the arguments now
spawn('p4.exe', ['changes', '-s', 'submitted']);

Ответ 19

Вы меняете опцию env?

Тогда посмотрите на этот ответ.


Я пытался порождать процесс узла и TIL, чтобы вы распространяли существующие переменные окружения при порождении, иначе вы потеряете переменную окружения PATH и, возможно, другие важные.

Это было исправление для меня:

const nodeProcess = spawn('node', ['--help'], {
  env: {
    // by default, spawn uses 'process.env' for the value of 'env'
    // you can _add_ to this behavior, by spreading 'process.env'
    ...process.env,
    OTHER_ENV_VARIABLE: 'test',
  }
});

Ответ 20

Если у вас возникла эта проблема с приложением, источник которого вы не можете изменить, подумайте о его вызове с переменной среды NODE_DEBUG, установленной в child_process, например, NODE_DEBUG=child_process yarn test. Это предоставит вам информацию о том, какие командные строки были вызваны в каком каталоге и, как правило, последняя деталь является причиной сбоя.

Ответ 21

Добавьте C:WindowsSystem32 в переменную среды path.

Действия

  • Перейдите на мой компьютер и свойства

  • Нажмите «Дополнительные настройки»

  • Затем в переменных среды

  • Выберите path, а затем нажмите на ссылку

  • Вставьте следующие, если они еще не присутствуют: C:WindowsSystem32

  • Закройте командную строку

  • Запустите команду, которую вы хотите запустить

Windows 8 Environment variables screenshot

Понравилась статья? Поделить с друзьями:
  • Error setting certificate verify locations cafile etc pki tls certs ca bundle crt capath none
  • Error setting audit daemon pid permission denied
  • Error spawn ebusy
  • Error setting aam
  • Error settime was not declared in this scope