Fix NPM No Such File Error on WSL2Janne 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
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 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
Finally, install the version you need:
$ nvm install 16
npm install and other commands should now work!