How to fix "throw er; // Unhandled 'error' event"?

Peter Thaleikis

Engineer. Maker. Open Source Fan. Backpacker

by Peter Thaleikis

Some errors are easy and simple. Quick fixes you get resolved in minutes. Others aren't and you got to dig in for much longer than you would like to. This was one of these for me. To make it a bit easier for other developers I'm sharing my solution here.

This problem seems to affect especially Linux users. I can't confirm it for sure as I run only Linux 🐧️ On my elementary the issue usually comes up when I try to run npm commands which are supposed to watch file changes (e.g. SCSS or JavaScript files). The related dev- and prod-commands work fine. It's only affecting watch-command and appears to be linked to a file-system incompatibility.

This particular case problem comes using Laravel mix on a project. On npm run watch I get this error messages after the compile step is finish:

      throw er; // Unhandled 'error' event

If supported watch-poll resolves the issue. But some libraries, like my starter for eleventy (this blog), aren't supporting poll and I needed to resort to a different approach. After spending some time researching and trying I've found a solution which works for now. I remove the node_modules-folder (rm -rf node_modules) and force-clear the NPM cache (npm cache clear --force) before reinstalling the node dependencies. Summarized in the following steps:

rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force
npm install

Please note: This removes also the lock-file. Thereby updating your project, make sure to test everything before you push the changes to production 🙏️

Update: Trick #2 - Stop all other NodeJS processes

If you have a number of node processes running this might be part of your issue. I've noticed the problem coming up more often if I've got a number of watch processes (for other projects) running. After stopping these and clearing the files as described above the issues was resolved.