Installing packages with yarntrace error spawn yarn enoent

This happens when I run expo install expo-permissions It explicitly returns me Installing 1 SDK 35.0.0 compatible native module using Yarn. yarn add expo-permissions@~7.0.0 spawn yarnpkg ENOENT Set

This happens when I run expo install expo-permissions

It explicitly returns me

Installing 1 SDK 35.0.0 compatible native module using Yarn.

yarn add expo-permissions@~7.0.0

spawn yarnpkg ENOENT

Set EXPO_DEBUG=true in your env to view the stack trace.

Which is strange because I don’t normally use Yarn. I use NPM to install dependencies.

I know this error has to do with my files or some path not being configured correctly. What I don’t know is which path it is that I have to change and how to do so.

Please let me know if there is any other relevant info that I should add here.

Community's user avatar

asked Nov 17, 2019 at 22:56

Wilfredo Casas's user avatar

Wilfredo CasasWilfredo Casas

3792 gold badges4 silver badges13 bronze badges

2

I had the same problem as you my solution and you perform the installation of yarn via npm:
npm i -g yarn
I believe this error is caused because he cannot find the symbolic link for yarnpkg. When executing this command, yarn will be updated and linked.

answered Feb 10, 2020 at 13:55

Guilherme Benevides's user avatar

You can just pass the flag —npm after the command.

expo install [package-name] --npm

answered Aug 6, 2020 at 13:06

Gabriel Veiga Cardoso's user avatar

1

Best solution for this would be using --npm flag

Example:

expo install pkname --npm,
expo update --npm,
expo upgrade --npm,

This is happened because you haven’t executed yarn install or yarn command.

Malakai's user avatar

Malakai

2,8818 gold badges34 silver badges49 bronze badges

answered Aug 11, 2021 at 3:03

Deepak Meena's user avatar

Yes, I tried many ways and finally, I found the solution.
The issue was different yarn package version.
So first of all, you need to upgrade yarn version lastest.

open terminal and type the following.

  1. npm install —global yarn

  2. expo update

Hope this solve your issue.

answered Apr 8, 2021 at 15:09

Sheng Li's user avatar

Sheng LiSheng Li

1192 silver badges4 bronze badges

I had a similar problem. You should install yarn in your system, since that’s what Expo CLI is trying to execute to install packages. For me my issue was that I did had yarn but I had an old version. I had to update my yarn version to 1.19.0. If you install this version it should work correctly.

I recommend using yvm to install and manage different versions of yarn. After you install yvm it is as easy to install yarn as yvm install <version>, so in this case you would do yvm install 1.19.0. And if you ever have to change versions because another project doesn’t work with 1.19.0 (sometimes it happens) you can just install another version and change between versions by doing yvm use <version>.

Hope this helps!

answered Nov 20, 2019 at 11:46

Mauricio's user avatar

MauricioMauricio

8092 gold badges13 silver badges26 bronze badges

This worked for me:

Latest Yarn Installation (from here)

curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt update && sudo apt install yarn

sudo apt update && sudo apt install --no-install-recommends yarn

Add this to your profile: export PATH="$PATH:/opt/yarn-[version]/bin" (the path may vary depending on where you extracted Yarn to)
In the terminal, log in and log out for the changes to take effect

yarn --version checks if the version is latest (1.0+).

Then expo update <version> (ex: 36.0.0)

Concideration:
Do not forget to check if you give attention to similar warning: «warning package-lock.json found. Your project contains lock files generated by tools other than Yarn.«

answered Dec 17, 2019 at 14:57

Giorgi Gvimradze's user avatar

Giorgi GvimradzeGiorgi Gvimradze

1,4231 gold badge14 silver badges32 bronze badges

«spawn yarnpkg ENOENT» usually indicates that the system cannot find the «yarnpkg» command.

npm i -g corepack

This worked for me.

answered Dec 25, 2022 at 1:59

ogncmn's user avatar

@TheDutchCoder

Version

4.5.6

Environment info

Steps to reproduce

  1. Globally install vue-cli
  2. Run vue create [myprojectname]

What is expected?

The project to be created

What is actually happening?

An error is thrown when creating the project (default options)

@TheDutchCoder

Apparently there was a stray yarn config that clashes with vue-cli. Odd.
I removed it and now it works.

@TheDutchCoder

That was premature, now there’s an error when actually creating the project:

 ERROR  Error: spawn yarn ENOENT
Error: spawn yarn ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:232:19)
    at onErrorNT (internal/child_process.js:407:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)

@TheDutchCoder
TheDutchCoder

changed the title
«Invalid version» on vue create command (clean install)

Error: spawn yarn ENOENT on vue create with a clean install

Sep 21, 2020

@LinusBorg

can you give us a little bit more information about your environment what is your node version what is your yarn version etc?

Also could you provide a little bit more information when exactly the error is occurring? you wrote that it happens after trying to create a project with default options — a screenshot of the terminal, showing which of the steps were already done or in progress before the error appeared would be helpful

@TheDutchCoder

Okay, so I just figured out that vue-cli requires yarn.
If I install yarn globally through Homebrew the create function works fine.

That might be worth adding to the docs? I’m still a little confused why it would require yarn though.

@LinusBorg

It does not require yarn. It work with both npm and yarn. And it checks which is available on your system and then chooses that. You can also force it to use one or the other with a flag. This is documented in the guide,. though could likely be more prominant.

For some reason, it seems to have falsely «detected» yarn on your system — maybe from a prior install was was not completely removed?

@TheDutchCoder

I uninstalled yarn completely and vue-cli only started working when I reinstalled yarn through Homebrew again.

Doesn’t seem to make a ton of sense (I only use npm but had yarn installed from waaaay back apparently). Other people are also having this issue by the way, see: #5690

@corepay

Same errors here with npm global install. using nvm do not want to cross-pollute node with brew-node.

vui ui allows me to create projects however. cli is broken here in my town

@mstjepan28

I had an issue when I deleted Yarn from windows that some files stayed in AppDataLocalYarn. Deleting them solved the problem for me

@shauryadhadwal

I also had the same issue. I am using Ubuntu.
I used vue-cli before, so there is a file create ~/.vuerc which saves all your presets.
In here, package manager was set as «yarn» which I no longer had. After deleting the file and using vue create,
I was prompted to select package manager. The issue was resolved post this.

Note: Before this, I installed yarn with which the error was resolved. But would recommend to use the above method.

jtbaker, bradtm2000, andersenmp, yafengli, itwondersteam, andres-k, Adrian-Fang, macdaddyaz, cznec, scottmo, and 27 more reacted with thumbs up emoji
wallaceb-dev reacted with hooray emoji
Mefistopel, soongon, alex-mos, and khackskjs reacted with heart emoji
rodolfo-santos and Sascha-Block reacted with rocket emoji

@andersenmp

I also had the same issue. I am using Ubuntu.
I used vue-cli before, so there is a file create ~/.vuerc which saves all your presets.
In here, package manager was set as «yarn» which I no longer had. After deleting the file and using vue create,
I was prompted to select package manager. The issue was resolved post this.

Note: Before this, I installed yarn with which the error was resolved. But would recommend to use the above method.

I’ve got the same issue after removing yarn in Windows 10. Package Manager was set to yarn on my ~/.vierc file

{
«useTaobaoRegistry»: false,
«packageManager»: «yarn»
}

@andres-k

I also had the same issue. I am using Ubuntu.
I used vue-cli before, so there is a file create ~/.vuerc which saves all your presets.
In here, package manager was set as «yarn» which I no longer had. After deleting the file and using vue create,
I was prompted to select package manager. The issue was resolved post this.

Note: Before this, I installed yarn with which the error was resolved. But would recommend to use the above method.

Thank you. I also ran into the same issue using ASDF for managing different node environments and this gave me a lot of headache.

Deleting the ~/.vuerc file solved the issue.

@stuheiss

tl;dr If you previously installed yarn with brew run «brew unlink yarn && brew link yarn»

I had the same issue immediately after updating vue-cli. This apparently removed /usr/local/bin/yarn which is the symlink created by running «brew install yarn» and points to /usr/local/Cellar/yarn/1.22.10/bin/yarn. Fix is to recreate the symlink /usr/local/bin/yarn by running «brew unlink yarn && brew link yarn»

@aritro-rakshit

For Windows users uninstall and reinstall yarn it will solve your issue.
npm uninstall yarn
npm install —global yarn

@pointer

@binodnepali

I also came across the same issue. I have npm and yarn both installed globally in my system. But the vue-cli (4.1.2) could not choose (or prompt me to choose) the package manager. I have fixed it by setting a flag vue create -m npm project-name and it worked for me.

@zhuweiyou

@tako-sphynx

I also had the same issue. I am using Ubuntu. I used vue-cli before, so there is a file create ~/.vuerc which saves all your presets. In here, package manager was set as «yarn» which I no longer had. After deleting the file and using vue create, I was prompted to select package manager. The issue was resolved post this.

Note: Before this, I installed yarn with which the error was resolved. But would recommend to use the above method.

Hi. I have the same error after npm create some-project. want to use your solution but can’t find ~/.vuerc file. Can you help me somehow?

How to fix the installing packages with yarn trace error spawn yarn enoent error

When does the installation of packages with yarn trace error spawn yarn enoent occur?

Most of the time, the error arises when there is no specific tool in the system. Let’s take an example to illustrate this. So we want to create a Nuxt.js project. During the setup, we are being asked different things, such as how you want to call your project, what are the libraries you want to install, etc.

One of those configurations asks what development tools you want to use. And there are two options: either yarn or npm. As the npm is already on the system (because we need npm to even start creating Nuxt.js), choosing npm will install the needed modules. However, if you choose the yarn, another package manager, then you will need to have yarn installed. And in case there is no yarn installed globally, you will get this error:

This case was mentioned in the Nuxt project creation post.

Anyway, there is a simple solution to this problem. All you need to do is to install yarn globally:

npm install -g yarn

Usually, it doesn’t really matter what were you trying to achieve or what to install. The problem occurs when there is some problem with yarn. Either the installation is corrupted, there is no path set for the yarn, or you don’t have it installed at all. Installing it globally solves the problem in case you don’t have it in your system.

But what if the yarn is installed and it still doesn’t work?

If you know that your yarn installation is valid and not corrupted, then the previous solution won’t help. Anyway, it is still related to some of the commands or working directory not existing. But how do we know where is the problem specifically? The generic error message doesn’t help that much, except that it says there is a problem with spawn. It can be a big headache to understand what is the problem if your application has a big codebase.

There was a great solution for finding the problematic code place shared by the user Jiaji Zhou on StackOverflow. You need to add this code snippet into the file that starts your application (by default, it is called index.js):

And when the error occurs again, the information needed to identify what is this all bout, will be printed to the console. In this way, you will know where you should focus to fix it.

So you know what command was failed to execute. How you should fix it right now? There are a few things you should check:

  • If you are using Windows, a possibility is that there is a problem with the path variable. Check if the path is set correctly in the environment variables.
  • You are using an outdated/corrupted version of a package. Reinstalling it could fix the problem.

Источник

Latest version cannot create anything without yarn #3421

Comments

Phoscur commented Feb 5, 2019

Version

Environment info

Steps to reproduce

  1. use clean machine
  2. install node 10 with npm, no yarn
  3. npm i -g @vue/cli
  4. vue create hello

What is expected?

Wizard starts, asking for options e.g. which package manager to use.

What is actually happening?

Yarn is missing (although not needed), wizard and childprocess crash.

Any attempts in forcing npm as a packageManager (via .vuerc) were futile, either returning the same error or this one:

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

sodatea commented Feb 5, 2019

Can’t reproduce.
Unless you’ve got yarnpkg installed but no yarn command presents, I don’t see any code logic to produce such errors.

Phoscur commented Feb 6, 2019

Tried to reproduce again and failed (today was my third install of version 3.4.0).
CLI 3.4.0 now also let’s me choose presets I have created with version 3.3.0.
Issue might be still reproducible with a clean machine. Or maybe I just had a bad download : /
closing.

SamuelEarl commented Oct 17, 2019 •

I ran into a similar issue with a very similar error message, which I could not figure out for a long time. I wanted to record what I discovered in the hope that it could help someone in the future.

When I would create new Vue projects with vue create

it would create a yarn.lock file, even though I was using npm. So I tried uninstalling Yarn and removing all necessary Yarn files to prevent this from happening. After uninstalling Yarn, I got a Error: spawn yarn ENOENT message in my terminal (very similar to the one shown above) and I could not create any Vue projects.

After trying a bunch of things, I reinstalled Yarn and everything worked again. I could see that Vue CLI was clearly creating projects with Yarn, but I didn’t know why. And then I came across this post: #1300. I also read the documentation that explains the .vuerc file here: https://cli.vuejs.org/guide/creating-a-project.html#vue-create. That solved everything. I opened the

/.vuerc file and set the package manager to npm and all is well now.

karl93rus commented Oct 27, 2019

@SamuelEarl Thank you for the hint with .vuerc . That solved a problem!

davidmeirlevy commented Jan 11, 2020

had the same issue.
i removed

/.vuerc file, and now it works.

anubhavcodes commented Jan 17, 2020

I had the same problem today. I had installed yarn before via npm and then removed it recently. npm list had only two packages.

/.vuerc and and some Vue CLI selected yarn as the package manager. It will be interesting to see how vuecli determines the package manager installed on the host.

/.vuerc file fixed the problem for me.

ikmrgrv commented Mar 8, 2020

I had yarn installed through brew .
Uninstalling yarn and reinstalling it worked for me.

I guess in my case, I tampered some core files for node while I was switching between different versions of nodejs using nvm. In the process I modified some globally installed packages, which is where I guess, @vue/cli was tampered.

hayashi-ay commented Mar 10, 2020 •

I had the same problem and removing the .vuerc worked fine for me.

I’m using nodebrew for Node.js version manegement.
I had run vue create with v12.10.0 of node and it was okay that time. (I think I had installed yarn via npm .)
Then, I switched node version to v12.16.1 by nodebrew use v12.16.1 and run vue create .
The following error message shows up this time.

I removed the .vuerc :

and after vue create it became :

sodatea commented Mar 10, 2020

@hayashi-ay
An additional tip: if you are outside China, maybe useTaobaoRegistry: false works better for you.
We set this flag by pinging different registries on the first run. If it’s set to true than a mirror registry inside China is used to install dependencies.
But the mirror is inside China so most other users won’t benefit from it. So if you are not in China, I guess there’s a misjudgment in the pinging process. Set it back to false can avoid potential issues in the future.

hayashi-ay commented Mar 10, 2020

@sodatea thanks for explaining the useTaobaoRegistry . I’m in Japan, so I switched it to false .

hayashi-ay commented Mar 11, 2020

@sodatea Hi there, I’ve just come up with three questions. Please let me know if it doesn’t bother you.

  • why the mirror registry inside China is necessary?
  • what is the difference between the default and the mirror?
  • what kind of issue I may encounter if I set the option true?

I also glanced at the pinning process and found that the option is likely to be true in Japan because of the geographic factor.
Can I create PR about the modification of the process?

The output of pinning to the both registries is below. I found that the taobao registry win the promise race with a higly probability.

sodatea commented Mar 11, 2020 •

@hayashi-ay I guess because Japan is so close to China, the connectivity is fine. Then you’ll be fine with either registry.

what kind of issue I may encounter if I set the option true?

In other countries, it may take too long to download from the mirror registry: #5144 #1385

  • why the mirror registry inside China is necessary?
  • what is the difference between the default and the mirror?

In China, home broadband users are likely to face QoS issues when accessing oversea servers. So downloading from the official npm registry may be slow unless you are using commercial broadband.

Besides, due to the GFW, many websites are not accessible in China including most Google servers (making chromedriver binary CDN inaccessible). I also believe that connection Amazon S3 storage (which hosts binary files for many npm packages) is throttled so that downloading is extremely slow.

Источник

Error: spawn yarn ENOENT on vue create with a clean install #5891

Comments

TheDutchCoder commented Sep 21, 2020 •

Version

Environment info

Steps to reproduce

  1. Globally install vue-cli
  2. Run vue create [myprojectname]

What is expected?

The project to be created

What is actually happening?

An error is thrown when creating the project (default options)

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

TheDutchCoder commented Sep 21, 2020

Apparently there was a stray yarn config that clashes with vue-cli. Odd.
I removed it and now it works.

TheDutchCoder commented Sep 21, 2020

That was premature, now there’s an error when actually creating the project:

LinusBorg commented Sep 21, 2020

can you give us a little bit more information about your environment what is your node version what is your yarn version etc?

Also could you provide a little bit more information when exactly the error is occurring? you wrote that it happens after trying to create a project with default options — a screenshot of the terminal, showing which of the steps were already done or in progress before the error appeared would be helpful

TheDutchCoder commented Sep 21, 2020

Okay, so I just figured out that vue-cli requires yarn.
If I install yarn globally through Homebrew the create function works fine.

That might be worth adding to the docs? I’m still a little confused why it would require yarn though.

LinusBorg commented Sep 21, 2020 •

It does not require yarn. It work with both npm and yarn. And it checks which is available on your system and then chooses that. You can also force it to use one or the other with a flag. This is documented in the guide,. though could likely be more prominant.

For some reason, it seems to have falsely «detected» yarn on your system — maybe from a prior install was was not completely removed?

TheDutchCoder commented Sep 21, 2020 •

I uninstalled yarn completely and vue-cli only started working when I reinstalled yarn through Homebrew again.

Doesn’t seem to make a ton of sense (I only use npm but had yarn installed from waaaay back apparently). Other people are also having this issue by the way, see: #5690

corepay commented Sep 27, 2020 •

Same errors here with npm global install. using nvm do not want to cross-pollute node with brew-node.

vui ui allows me to create projects however. cli is broken here in my town

mstjepan28 commented Sep 28, 2020

I had an issue when I deleted Yarn from windows that some files stayed in AppDataLocalYarn. Deleting them solved the problem for me

shauryadhadwal commented Nov 4, 2020 •

I also had the same issue. I am using Ubuntu.
I used vue-cli before, so there is a file create

/.vuerc which saves all your presets.
In here, package manager was set as «yarn» which I no longer had. After deleting the file and using vue create,
I was prompted to select package manager. The issue was resolved post this.

Note: Before this, I installed yarn with which the error was resolved. But would recommend to use the above method.

andersenmp commented Dec 27, 2020

I also had the same issue. I am using Ubuntu.
I used vue-cli before, so there is a file create

/.vuerc which saves all your presets.
In here, package manager was set as «yarn» which I no longer had. After deleting the file and using vue create,
I was prompted to select package manager. The issue was resolved post this.

Note: Before this, I installed yarn with which the error was resolved. But would recommend to use the above method.

I’ve got the same issue after removing yarn in Windows 10. Package Manager was set to yarn on my

<
«useTaobaoRegistry»: false,
«packageManager»: «yarn»
>

andres-k commented Feb 4, 2021

I also had the same issue. I am using Ubuntu.
I used vue-cli before, so there is a file create

/.vuerc which saves all your presets.
In here, package manager was set as «yarn» which I no longer had. After deleting the file and using vue create,
I was prompted to select package manager. The issue was resolved post this.

Note: Before this, I installed yarn with which the error was resolved. But would recommend to use the above method.

Thank you. I also ran into the same issue using ASDF for managing different node environments and this gave me a lot of headache.

/.vuerc file solved the issue.

stuheiss commented Mar 26, 2021

tl;dr If you previously installed yarn with brew run «brew unlink yarn && brew link yarn»

I had the same issue immediately after updating vue-cli. This apparently removed /usr/local/bin/yarn which is the symlink created by running «brew install yarn» and points to /usr/local/Cellar/yarn/1.22.10/bin/yarn. Fix is to recreate the symlink /usr/local/bin/yarn by running «brew unlink yarn && brew link yarn»

aritro-rakshit commented Jun 15, 2021 •

For Windows users uninstall and reinstall yarn it will solve your issue.
npm uninstall yarn
npm install —global yarn

Источник

I’m on a 2015 MacBook Pro and for the life of me, I cannot see why I cannot make an .exe build (Windows) on my Mac.

❯ quasar build --mode electron --target win

 Build mode........ electron
 Pkg quasar........ v1.9.8
 Pkg @quasar/app... v1.6.0
 Debugging......... no
 Publishing........ no

 app:quasar-conf Reading quasar.conf.js +0ms
 app:webpack Extending Renderer process Webpack config +3s
 app:webpack Extending Main process Webpack config +29ms
 app:artifacts Cleaned build artifact: "/Users/dan/code/ss/app/scr/dist/electron" +36ms
 app:generator Generating Webpack entry point +3ms
 app:build Building... +9ms

 Renderer process ███████████               building [44%] 288/289 modules 1 active
 Main process     █████████████████████████ [100%] in ~11s


 Renderer process █████████████████████████ [100%] in ~17s
 Main process     █████████████████████████ [100%] in ~11s



Version: webpack 4.41.6
Time: 17180ms
Built at: 03/07/2020 7:51:18 PM
                                         Asset       Size  Chunks                         Chunk Names
                          css/app.e85ae70d.css    191 KiB       1  [emitted] [immutable]  app
            fonts/KFOkCnqEu92Fr1MmgVxIIzQ.woff   19.9 KiB          [emitted]              
           fonts/KFOlCnqEu92Fr1MmEU9fBBc-.woff     20 KiB          [emitted]              
           fonts/KFOlCnqEu92Fr1MmSU5fBBc-.woff   19.9 KiB          [emitted]              
           fonts/KFOlCnqEu92Fr1MmWUlfBBc-.woff   19.9 KiB          [emitted]              
           fonts/KFOlCnqEu92Fr1MmYUtfBBc-.woff   19.9 KiB          [emitted]              
               fonts/KFOmCnqEu92Fr1Mu4mxM.woff   19.8 KiB          [emitted]              
       fonts/flUhRq6tzZclQEJ-Vdg-IuiaDsNa.woff   77.7 KiB          [emitted]              
fonts/flUhRq6tzZclQEJ-Vdg-IuiaDsNcIhQ8tQ.woff2   59.4 KiB          [emitted]              
                                    index.html  873 bytes          [emitted]              
                                       js/2.js   12.1 KiB       2  [emitted]              
                                       js/3.js   1.64 KiB       3  [emitted]              
                                       js/4.js  431 bytes       4  [emitted]              
                                     js/app.js   5.01 KiB       1  [emitted]              app
                                  js/vendor.js    231 KiB       0  [emitted]              vendor
Entrypoint app = js/vendor.js css/app.e85ae70d.css js/app.js



Version: webpack 4.41.6
Time: 11191ms
Built at: 03/07/2020 7:51:12 PM
           Asset       Size  Chunks             Chunk Names
electron-main.js   10.1 KiB       0  [emitted]  electron-main
    package.json  590 bytes          [emitted]  
Entrypoint electron-main = electron-main.js

 app:spawn Running "yarn install --production" +18s

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

  Error: spawn yarn ENOENT
  
  - child_process.js:240 Process.ChildProcess._handle.onexit
    internal/child_process.js:240:19
  
  - child_process.js:415 onErrorNT
    internal/child_process.js:415:16
  
  - next_tick.js:63 process._tickCallback
    internal/process/next_tick.js:63:19
  

Emitted 'error' event at:
  
  - child_process.js:246 Process.ChildProcess._handle.onexit
    internal/child_process.js:246:12
  
  - child_process.js:415 onErrorNT
    [... lines matching original stack trace ...]

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

Понравилась статья? Поделить с друзьями:
  • Installing driver error mediatek driver not detected
  • Installing build dependencies finished with status error
  • Installing build dependencies done getting requirements to build wheel error
  • Installing backup error
  • Installer ошибка при получении данных