Spawn c windows system32 cmd exe enoent

This is my script : var exec = require('child_process').exec; exec('dir', function(error, stdout, stderr) { // 'dir' is for example if (error) { console.error(`exec error: ${er...

This is my script :

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

    exec('dir', function(error, stdout, stderr) {  // 'dir' is for example
      if (error) {
        console.error(`exec error: ${error}`);
        return;
      }
      console.log(`stdout: ${stdout}`);
      console.log(`stderr: ${stderr}`);
    });

And in the console I have :

exec error: Error: spawn C:Windowssystem32cmd.exe; ENOENT

Someone can help me ?

asked Jul 19, 2016 at 12:08

Jiohn Dioe's user avatar

5

This can also be caused if you are feeding in ExecOptions the options parameter, specifically ‘cwd’, and the path you provide is invalid

e.g:

cp.exec(<path_to_executable>, {
  cwd: <path_to_desired_working_dir>
}, (err, stdout, stderr) => {
  //......
})

If is not valid, the callback will be called with err equal to

Error: spawn C:Windowssystem32cmd.exe ENOENT

answered Nov 19, 2019 at 10:05

hugeandy's user avatar

hugeandyhugeandy

1831 silver badge6 bronze badges

1

I got to resolve the issue the problem is to remove the semicolon(;) from an end of the
ComSpec path C:WindowsSystem32cmd.exe

Mycomputer>properties>Advance System Settings>Environment Variables>System Variables

add this path:
enter image description hereComSpec C:WindowsSystem32cmd.exe

answered Mar 9, 2019 at 7:02

sudheer nunna's user avatar

0

The problem for me was that my solution directory was on a different drive than windows. Creating my solution on my C drive solved the issue.

Cody Gray's user avatar

Cody Gray

236k50 gold badges486 silver badges567 bronze badges

answered Feb 9, 2021 at 15:09

Ruan's user avatar

RuanRuan

3,72410 gold badges55 silver badges85 bronze badges

Increasing the maxBuffer solved the problem for me.

const child_process = require('child_process');

var command = 'git ls-files . --ignored --exclude-standard --others';

child_process.execSync(command, {
   maxBuffer: 1024 ** 6,
});

answered Jan 19, 2022 at 15:50

Abdul Samad's user avatar

Error: spawn C:windowssystem32cmd.exe ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
    at onErrorNT (internal/child_process.js:465:16)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'spawn C:\windows\system32\cmd.exe',
  path: 'C:\windows\system32\cmd.exe',
  spawnargs: [ '/d', '/s', '/c', '"which ansible-lint"' ],
  cmd: 'which ansible-lint',
  stdout: '',
  stderr: ''
}
Error: spawn C:windowssystem32cmd.exe ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:269:19)
    at onErrorNT (internal/child_process.js:465:16)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'spawn C:\windows\system32\cmd.exe',
  path: 'C:\windows\system32\cmd.exe',
  spawnargs: [ '/d', '/s', '/c', '"whereis ansible-lint"' ],
  cmd: 'whereis ansible-lint',
  stdout: '',
  stderr: ''
}
Path for lint:  undefined
Validating using ansible syntax-check
not a playbook...

Complete error reporting information

Complete error reporting information:
cannot start docker-compose application. Reason: error invoking remote method ‘compose action’: error: spawn C:windowssystem32cmd.exe enoent

Solving process

When installing MongoDB, the installation method is to run the command in the CMD window to pull the MongoDB image for installation, and habitually delete the configuration file after installation. Therefore, it is thought that this configuration file may be missing. Therefore, MongoDB is deleted from the docker desktop, and a path is selected for reinstallation.

Solution (for reference only)

Create a folder under any path (here is my path)

D:Program Filesdocker-mongodb

And put the docker-compose.yml configuration file in the folder (the following is the content of the configuration file)

version: '3.7'
services:
  mongodb_container:
    image: mongo:latest
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: rootpassword
    ports:
      - 27017:27017
    volumes:
      - mongodb_data_container:/data/db

volumes:
  mongodb_data_container:

Open CMD as an administrator and enter the path to the docker-compose.yml configuration file, that is, execute the command docker-compose up – d
in the folder just created. Open the docker desktop again and you can use mongodb normally
enter Mongo admin – U root – P password for testing

be careful

The mongodb version number and root password here can be modified in the configuration file of. YML

Read More:

Содержание

  1. spawn C:Windowssystem32cmd.exe ENOENT error with childProcess.exec() on Debugger #28271
  2. Comments
  3. atif089 commented Jun 9, 2017 •
  4. weinand commented Jun 14, 2017 •
  5. atif089 commented Jun 14, 2017
  6. atif089 commented Jun 15, 2017
  7. weinand commented Jun 15, 2017
  8. Electron (Packaged): Windows 10 spawn ENOENT error #135
  9. Comments
  10. byfareska commented Apr 23, 2019
  11. rexn8r commented Jul 12, 2019
  12. bencevans commented Jul 12, 2019
  13. rexn8r commented Jul 12, 2019
  14. Error: spawn cmd ENOENT in VS code #1818
  15. Comments
  16. mishra1207 commented Nov 27, 2019
  17. lcampos commented Dec 30, 2019
  18. mishra1207 commented Jan 2, 2020
  19. Problem with npm start (error : spawn cmd ENOENT)
  20. 5 Answers 5
  21. Not the answer you’re looking for? Browse other questions tagged node.js reactjs windows git-bash or ask your own question.
  22. Linked
  23. Related
  24. Hot Network Questions
  25. Subscribe to RSS
  26. Spawn c windows system32 cmd exe enoent
  27. Intelligent Recommendation
  28. Startup failure report: spawn cmd ENOENT error
  29. Eggjs start report spawn tail ENOENT error
  30. One nodejs Error: spawn convert ENOENT
  31. Recipe terminated with fatal error: spawn xelatex ENOENT
  32. Recipe terminated with fatal error: spawn latexmk ENOENT.

spawn C:Windowssystem32cmd.exe ENOENT error with childProcess.exec() on Debugger #28271

Steps to Reproduce:

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

weinand commented Jun 14, 2017 •

@atif089 I cannot reproduce this (because I do not know the value of ‘execPath’).

Please provide a small code snippet that I can use to reproduce the problem (and please real code and not a screenshot since I do not want to enter it by typing).

Thanks for the follow-up @weinand. Here’s all the code from the actual screenshot.

This file works fine when I run it in the terminal (both cmd and the integrated one in VS Code) but then when I run it by pressing F5 I see the error mentioned. I tried running VS Code as Administrator assuming that might make difference but there was no change.

And this file was working fine in at least until version 1.10

I figured this has nothing to do with VS code. The exec command fails because the resolved cwd path was invalid and it didn’t exist.

When I was running it through the terminal, I was always in the appropriate directory and that is why the command was working fine.

weinand commented Jun 15, 2017

@atif089 thanks for investigating (and resolving) the issue.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

Electron (Packaged): Windows 10 spawn ENOENT error #135

I’m getting something like that but on Windows 10 (on ubuntu works fine).
https://stackoverflow.com/questions/17951133/spawn-enoent-error

I’ve switched from 1.7.0 to 1.6.1 and it works on both OS.

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

I am also having the same error after packaging the app..

I did revert back to 1.6.1 but still no luck.

Check environment variable and it has «C:WINDOWSsystem32cmd.exe» in the path variable.

any pointer as to how to resolve this issue?

@rexn8r what do you mean by packaging the app?

when i create app package using electron-packager and run the exe with asar file, the plugin throws the error.

If i run the electron app in development environment i.e. using npm start command from node.js command window, the plug-in works absolutely fine.

the package folder structure created by electron-packager is:

app.exe
— resources (folder)
—|__ (under resource folder) app.asar (all the app files are packaged in it with html, javascript, node modules etc)

i unpacked the asar file and node module folder did have the screen-shot files. so its not that the packager is missing files.

Источник

Error: spawn cmd ENOENT in VS code #1818

Hi,
I am getting following error while running command- SFDX: Authorize an Org in VS Code:
Error: spawn cmd ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:264:19)
at onErrorNT (internal/child_process.js:456:16)
at processTicksAndRejections (internal/process/task_queues.js:77:11) <
errno: ‘ENOENT’,
code: ‘ENOENT’,
syscall: ‘spawn cmd’,
path: ‘cmd’,
spawnargs: [
‘/c’,
‘start’,
‘»»‘,
‘/b’,
‘https://login.salesforce.com//services/oauth2/authorize?response_type=code^&client_id=PlatformCLI^&redirect_uri=http%3A%2F%2Flocalhost%3A1717%2FOauthRedirect^&state=13f03582c57b^&prompt=login^&scope=refresh_token%20api%20web^&code_challenge=0q6hC3VWjMYLBKGHzLGm8g-NkJORu5ASRMfbdxDRyT0’
]
>

Could you please help me on this?
I have checked my configs and seems to be good.

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

@mishra1207 can you provide the following details on your setup:

If you are running on a Windows system I’ve seen similar errors happening when the System Environment variable PATH does not include the CLI’s path.

I was able to resolve the issue.
It was happening due to proxy settings in my company provided laptop. After removing them it started working.
Thank you for your response.

Источник

Problem with npm start (error : spawn cmd ENOENT)

I have a problem with my application. Because before when I created an application it worked, but now, it shows me this error and I do not know why and the things I have to do to fix it.

I checked some stackoverflow topics but everywhere I checked, it was not really an answer that worked.

yKhRr

5 Answers 5

Add C:WindowsSystem32 to the global PATH environment variable.

Solution 1

Solution 2

If the first one doesn’t work follow the 2nd steps. Navigate to your project folder and type this command >>>

Solution 3

Downgrade react-scripts in package.json file

agMKZ

I had the same problem after I tried to install Mongo DB. I found out that this problem only exists with react-scripts@3.0.0. Try to reinstall your npm with a different react script version. Simply go to your folder in command and reinstall like this:

After that the app worked for me again.

photo

For all those Who’ve come to this problem from react scripts not starting. The solution is

urGUZ

Not the answer you’re looking for? Browse other questions tagged node.js reactjs windows git-bash or ask your own question.

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.11.3.40639

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Spawn c windows system32 cmd exe enoent

This problem occurred when running vue ui. I forgot to take the specific screenshots, but the solution to this problem is basically the same, all because of the missing part of the user environment variables due to setting conflicts.

Adding System32 variables to user environment variables will probably solve this problem.

4c4eef12f052946d29fc084d67b1116f

b5ac245a6ddce3cc714951c81162e4e9

Intelligent Recommendation

8513e6651bb600d8a10a0ee7beb4987b

Startup failure report: spawn cmd ENOENT error

spawn cmd ENOENT Npm start error when starting, and then checked Baidu said that because the port is occupied, did not want to understand but killed the occupied port with the command line or an error.

Eggjs start report spawn tail ENOENT error

Start eggjsnpm run startReport an error while usingnpm run devno problem Develop window 7, used by the computer, used to use the systemcmdExecute the relevant command and throw the following error: Ca.

One nodejs Error: spawn convert ENOENT

the reason: I used itnode-galleryBut not installedimagemagick. You may or may not have the required program, the error prompted by nodejs is too obvious, but there is experience to find.

d873796ec471b52ae984f5d37e28ae3c

Recipe terminated with fatal error: spawn xelatex ENOENT

Recipe terminated with fatal error: spawn latexmk ENOENT.

Analysis Version info: VS code:1.50.0, Tex Live:2019/Debian, LaTex Workshop:8.13.2 Action Make sure your operation is correct by referencing to official guideline and VS Code + LaTeX. Install TEXLIVE.

Источник

Error: spawn cmd.exe ENOENT solution

tags: front end  vue  node.js  vue.js  ajax

This problem occurred when running vue ui. I forgot to take the specific screenshots, but the solution to this problem is basically the same, all because of the missing part of the user environment variables due to setting conflicts.

Adding System32 variables to user environment variables will probably solve this problem.

Intelligent Recommendation

Electron desktop program spawn ** ENOENT error

Electron desktop program spawn ** ENOENT error Wrong phenomenon solution Error troubleshooting steps Solution Wrong phenomenon useElectronAfter the desktop program is packaged, it is executed Appear s…

Spawn ** ENOENT error after electron packing

For some reason, at the company level, I was asked to write a burning tool for the factory workers to produce some equipment and burn some things into the equipment. Mainly based on electron to do, th…

Startup failure report: spawn cmd ENOENT error

spawn cmd ENOENT Npm start error when starting, and then checked Baidu said that because the port is occupied, did not want to understand but killed the occupied port with the command line or an error…

Eggjs start report spawn tail ENOENT error

Start eggjsnpm run startReport an error while usingnpm run devno problem Develop window 7, used by the computer, used to use the systemcmdExecute the relevant command and throw the following error: Ca…

More Recommendation

One nodejs Error: spawn convert ENOENT

the reason: I used itnode-galleryBut not installedimagemagick. You may or may not have the required program, the error prompted by nodejs is too obvious, but there is experience to find….

Error: spawn D:softwarenodejsnode.exe ENOENT

After Win10 installed node, NPM error, the following is an error message: Enter NPM any command to report an error C: Program Files nodejs node.exe file exists Nodejs has been reinstalled N time…

yooakim opened this issue a year ago · comments

  • I have tried with the latest version of Docker Desktop
  • I have tried disabling enabled experimental features
  • I have uploaded Diagnostics
  • Diagnostics ID: 8B2EA6F7-4A97-48C4-9FB6-3E355C996E1E/20210916130539

Actual behavior

When I try to stop the application started via Docker Compose I the the error:

Cannot stop Docker Compose application. Reason: Error invoking remote method 'compose-action': Error: spawn C:Windowssystem32cmd.exe ENOENT

Here’s a screen recording:
docker-desktop-issue

Expected behavior

I expected the app to be stopped.

Information

The app was created from the appwrite.io getting started guide.

  • Windows Version: 10.0.22000
  • Docker Desktop Version: 4.0.1
  • WSL2 or Hyper-V backend? WSL2
  • Are you running inside a virtualized Windows e.g. on a cloud server or a VM: No

I had that same problem and the fix was:

  1. Restart each docker container (I did this using CLI).
    docker container ls -a
    docker container restart <container_id>
  2. After that check if all of them are running, if not log ones that exited.
    docker container logs <container_id>
  3. Look for some errors, in my case there was one config file missing.
  4. Fix error 😉

Issues go stale after 90 days of inactivity.
Mark the issue as fresh with /remove-lifecycle stale comment.
Stale issues will be closed after an additional 30 days of inactivity.

Prevent issues from auto-closing with an /lifecycle frozen comment.

If this issue is safe to close now please do so.

Send feedback to Docker Community Slack channels #docker-for-mac or #docker-for-windows.
/lifecycle stale

Hello, i’ve had the same when i changed the name folder where was my docker-compose. i had to change the old name folder

how do you restart the server again? I tried to restart the server, but that error occurs

@levi956 I run «docker-compose start» from dir where has appwrite folder. Try Quit Docker Desktop (in Windows), and then try run/stop server.
image

Thank you it worked for me. All you have to do is go inside appwrite directory and docker-compose start to start or docker-compose stop to stop

I have deleted the appwrite directory what should I do?

Closed issues are locked after 30 days of inactivity.
This helps our team focus on active issues.

If you have found a problem that seems similar to this, please open a new issue.

Send feedback to Docker Community Slack channels #docker-for-mac or #docker-for-windows.
/lifecycle locked

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

Понравилась статья? Поделить с друзьями:
  • Spatial media metadata injector скачать windows
  • Spatial media metadata injector для windows
  • Spartan браузер скачать для windows 10 с официального сайта
  • Spark почтовый клиент для windows скачать
  • Spark почта для windows 10 скачать