Step-by-Step Guide
- Update the Package Index
Open a terminal and update the package index to ensure you have the latest information about available packages:
sudo apt update
- Install Node.js
Debian’s default repositories contain an older version of Node.js. To install the latest version, use the NodeSource repository. First, install the necessary dependencies:
sudo apt install curl software-properties-common
- Add NodeSource Repository
Usecurl
to add the NodeSource repository:
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
This command will add the NodeSource repository for Node.js 16.x.
- Install Node.js and npm
Install Node.js and npm using theapt
package manager:
sudo apt install nodejs
- Verify Node.js Installation
Check the Node.js version to ensure it is installed correctly:
node -v
You should see the Node.js version information displayed.
- Verify npm Installation
Check the npm version to ensure it is installed correctly:
npm -v
You should see the npm version information displayed.
- Install Build Tools (Optional)
Some npm packages require build tools to compile native add-ons. Install these tools using the following command:
sudo apt install build-essential
- Create a Simple Node.js Application
Create a new directory for your Node.js application:
mkdir myapp
cd myapp
Initialize a new Node.js project:
npm init -y
Create a simple app.js
file:
nano app.js
Add the following code to the app.js
file:
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}/`);
});
Save and close the file.
- Run the Node.js Application
Start the Node.js application:
node app.js
You should see a message indicating that the server is running. Open your web browser and visit http://127.0.0.1:3000
. You should see the message “Hello, World!”.
- Install Global npm Packages (Optional)
You can install npm packages globally using the-g
flag. For example, to install the popularexpress
framework globally, use:bash npm install -g express