Fix NPM No Such File Error on WSL2

Janne Kemppainen |

I was working on a Node.js project and decided to run it on top of Windows Subsystem for Linux but it just wouldn’t work. The npm command would fail with a “no such file or directory error” like this:

$ npm install
/usr/bin/env: ‘bash\r’: No such file or directory

Trying to Google this issue pointed me towards issues with Git, and initially I thought that it must’ve been because I had cloned the repository with Git for Windows. After all, the line endings in Windows and Linux differ from one another, Linux has \n while Windows uses \r\n.

The real reason for this error was that I had installed Node.js on Windows, and it became automatically visible in WSL2! I had forgot to install Node on WSL2 it found the executable from the Windows side, as we can see from the which command:

$ which npm
/mnt/c/Program Files/nodejs//npm

Since you can execute Windows programs that are in the system path from WSL (try to run explorer.exe, for example) the npm executable from Program Files was also there, causing confursion. In contrast, if you don’t have any version of Node installed on your system the WSL prompt is going to suggest you to install one.

To fix this error you just have to install Node.js on WSL2. I recommend that you use nvm as it lets you manage the installations and easily switch between versions.

You can find the official stallation instructions here, but essentially you have to run this command:

$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

Restart the shell, start a new one, or run the commands that the installation scrips suggests, and you should be able to run the nvm command.

Finally, install the version you need:

$ nvm install 16

The npm install and other commands should now work!

Subscribe to my newsletter

What’s new with PäksTech? Subscribe to receive occasional emails where I will sum up stuff that has happened at the blog and what may be coming next.

powered by TinyLetter | Privacy Policy