Introduction
While trying to run a Node.js script using the command node script.js, you might encounter the following error: bash: node: command not found. This error message can be confusing, especially if you have already installed Node.js on your system. This article will guide you through troubleshooting and fixing this issue.
Checking Node.js Installation
Before diving into the solution, it's essential to check whether Node.js is installed on your system. You can do that by running the following command:
node -v
If Node.js is installed, it will display the Node.js version number (e.g., v14.17.3). However, if the node command is not found, you'll have to install Node.js or configure the system to locate the Node.js binary.
Installing Node.js
Suppose Node.js is not installed. In that case, you can install it by following the official Node.js website's instructions for your specific operating system here.
Using a Package Manager on Linux
If you are using a Linux distribution, you can install Node.js through a package manager such as apt (Ubuntu and Debian-based distributions) or dnf (Fedora and RHEL-based distributions). Here are the commands for installation:
# For Debian-based distributions
sudo apt-get update
sudo apt-get install nodejs
For RHEL-based distributions
sudo dnf install nodejs
Configuring PATH Variable
Once Node.js is installed, the system might not know the location of the Node.js binary immediately. This issue mostly affects Linux and macOS systems. You can fix this by adding the Node.js binary path to the system's PATH environment variable.
First, find the Node.js binary location by running:
which node
This command will output the path (e.g., /usr/bin/node). Now, open your shell configuration file (e.g., ~/.bashrc or ~/.zshrc) and add the following code at the end:
# For bash
export PATH=$PATH:/path/to/node/binary
For zsh
export PATH="$PATH:/path/to/node/binary"
Replace /path/to/node/binary with the actual node binary path. Save and close the file. Finally, reload your shell configuration using:
source ~/.bashrc
# Or for zsh
source ~/.zshrc