To install Node.js, npm, and PM2 on a new server, follow these steps:
1. Update your system's package index:
sudo apt-get update
2. Install Node.js and npm:
You can install Node.js using the NodeSource repository. First, add the NodeSource repository:
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
Then, install Node.js (this will also install npm):
sudo apt-get install -y nodejs
3. Verify the installation:
Check if Node.js and npm were installed correctly by running:
node -v npm -v
4. Install PM2:
PM2 is a process manager for Node.js applications. You can install it globally using npm:
sudo npm install pm2@latest -g
5. Verify PM2 installation:
Make sure PM2 was installed correctly by checking its version:
pm2 -v
6. (Optional) Set up PM2 to start on boot:
To ensure that your Node.js application restarts automatically after a server reboot, you can set up PM2 to start on boot:
pm2 startup
This will display a command that you need to run with sudo
to configure PM2 for your system.
Now your server should be ready with Node.js, npm, and PM2 installed and configured!
Optional, Add EJS!
1. Install EJS
Run the following command to install the EJS package:
npm install ejs
2. Set EJS as the View Engine
In your Express app's main file (e.g., app.js
or server.js
), set up EJS as the templating engine.
const express = require('express');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Define the directory for your views (optional, default is './views') app.set('views', path.join(__dirname, 'views')); // Ensure 'path' is imported
3. Create the views
Directory
By default, Express looks for EJS files in a folder named views
at the root of your project. Create this folder:
mkdir views
4. Create an EJS Template
Inside the views
folder, create an example EJS file, such as index.ejs
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Welcome</title>
</head>
<body>
<h1>Hello, <%= name %>!</h1>
</body>
</html>
5. Create a Route to Render the EJS File
Add a route in your Express app to render the index.ejs
file:
app.get('/', (req, res) => { res.render('index', { name: 'Raspberry Pi User' }); });
6. Start the Server
pm2 start index.js --watch
7. View Logs
pm2 logs index