To run the server in Node.js you need to follow the following steps: Create a Node.js file. Import the http module. Create server. Listening port. Handle requests and responses. Run the script.
Running the server in Node.js
How to run the Node.js server?
To run the server in Node.js, you need to follow the following steps:
1. Create a Node.js file:
Use Text editor or IDE Create a new Node.js file, such as server.js
.
2. Import the necessary modules:
Import the built-in http
module of Node.js to create the server.
<code class="javascript">const http = require('http');</code>
3. Create a server:
Use http.createServer()
to create a server. The server will listen on a specific port number.
<code class="javascript">const server = http.createServer((req, res) => { // 处理请求和响应 });</code>
4. Listening port:
Call the listen()
method to start the server on the specified port.
<code class="javascript">server.listen(3000, () => { console.log('服务器已启动,监听端口 3000'); });</code>
5. Processing requests and responses:
In the server's callback function, requests from the client can be processed and responses sent.
<code class="javascript">const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>欢迎访问 Node.js 服务端!</h1>'); });</code>
6. Run the script:
Use the following command to run the Node.js script in the command line:
<code>node server.js</code>
Advantages:
The above is the detailed content of How to run nodejs server. For more information, please follow other related articles on the PHP Chinese website!