When installing Node.js from apt, you may receive an outdated version of the engine. To install a recent version of Node.js, we can use NodeSource.
1. Pre-requirements
First, we need to install curl, a tool to perform HTTP requests.
sudo apt-get install curl
Encountered errors? Try running sudo apt-get update first.
2. Install the Node.js Setup Script
Now, let’s run the script provided by NodeSource for setting up Node.js.
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo bash -
Explanation:
curl -fsSL: This command downloads the setup script from NodeSource.https://deb.nodesource.com/setup_22.x: This is the URL of the setup script for Node.js version 22.x.| sudo bash -: This pipes the downloaded script tobashto execute it withsudoprivileges.
3. Install Node.js
Finally, use the package manager apt to install Node.js.
sudo apt-get install nodejs
This will install both Node.js and npm (Node Package Manager).
Verify Installation
Yes, that’s all! Now let’s check if the Node.js version is updated.
node -v
You should see the version of Node.js that was installed.
Additional Tips
-
Updating Node.js: If you need to update Node.js in the future, you can rerun the setup script for the desired version (e.g.,
setup_22.xfor version 22.x). -
Global Packages Permission Issue: If you encounter permission issues when installing global packages with
npm, you might want to change the directory wherenpmstores globally installed packages.mkdir ~/.npm-global npm config set prefix '~/.npm-global'Then add the following line to your
~/.profileor~/.bashrcfile:export PATH=~/.npm-global/bin:$PATHFinally, update your system variables:
source ~/.profile -
Using Node Version Manager (NVM): Alternatively, you can use Node Version Manager (NVM) to manage multiple Node.js versions on the same machine.
Install NVM:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bashLoad NVM:
source ~/.nvm/nvm.shInstall the latest Node.js version:
nvm install nodeUse a specific Node.js version:
nvm use <version>
That’s it! You now have the latest version of Node.js running on your Ubuntu system. Happy coding!