Home > Article > Web Front-end > How to start service in nodejs
How to start a service in Node.js? Create a Node.js project and install dependencies. Write server code and listen on the port. Start the server using the node command. Access the local address to test the service. Use PM2 management services.
How to start a service in Node.js
Starting a service in Node.js involves the following steps:
1. Create a Node.js application
Create a new Node.js project and install the necessary dependencies:
<code>mkdir my-app cd my-app npm init -y</code>
2. Write server code
Create a server.js
file containing the following code:
<code class="js">const express = require('express'); const app = express(); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server is listening on port 3000'); });</code>
3. Start the service
Use the node
command to start the server:
<code>node server.js</code>
This will start an Express server listening on port 3000.
4. Test the service
Visit http://localhost:3000
in your browser to confirm that the service is running.
5. Use PM2 to manage services
For production environments, use process managers such as PM2 to manage and monitor your services:
<code>npm install pm2 -g pm2 start server.js</code>
PM2 Will run your service in the background and provide restart, logging and load balancing functions.
The above is the detailed content of How to start service in nodejs. For more information, please follow other related articles on the PHP Chinese website!