Introduction
Node.js is a popular runtime environment for executing JavaScript code outside of a web browser. In this guide, we'll walk through the steps to install Node.js on Ubuntu 20.04, configure it, and run a sample app.
Prerequisites
Before proceeding, ensure you have:
- An Ubuntu 20.04 server
- Terminal or SSH access to your server
Steps to Install Node.js and npm
- Update Package Index: Before installing Node.js, update the package index on your Ubuntu server:
sudo apt update
- Install Node.js: Use the following command to install Node.js from the default Ubuntu repositories:
sudo apt install nodejs
- Install npm: npm is a package manager for Node.js. Install it using the following command:
sudo apt install npm
Run a Sample Node.js App
- Create a Directory: Create a directory for your Node.js app:
mkdir myapp
cd myapp
- Create a JavaScript File: Create a JavaScript file for your Node.js app. For example, create a file named
app.js
and add the following code:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
- Run the App: Use the following command to run the Node.js app:
node app.js
Your Node.js app should now be running and accessible at http://127.0.0.1:3000/
Conclusion
Congratulations! You have successfully installed Node.js and npm on your Ubuntu 20.04 server, configured them, and run a sample Node.js app. You can now start developing and running JavaScript applications using Node.js.