With the booming development of the mobile Internet, more and more web developers are beginning to shift from PC websites to mobile web application development. In this exciting era, Node.js has become one of the essential skills for front-end developers. I believe many beginners want to learn how to use Node.js to build a server and implement a simple web application. So today let us learn how to use Node.js to build a server and implement a basic HTML5 page.
1. What is Node.js
Node.js is a JavaScript runtime environment based on the Chrome V8 engine, which can run in a server environment outside of the browser. The emergence of Node.js allows front-end developers to directly use JavaScript for back-end development without having to learn other back-end languages and frameworks. This provides more possibilities for front-end development.
Features of Node.js:
2. Environment setup
Download the appropriate version from the official website https://nodejs.org/en/ Get the Node.js installation package on your computer and follow the prompts to install it.
Open the console, create a new folder and enter:
mkdir nodejs-server cd nodejs-server
Then create a server file in the directory and name it server .js:
touch server.js
Open the server.js file and enter the following code:
var http = require('http'); //引入http模块 var fs = require('fs'); //引入fs模块 var server = http.createServer(function(req, res){ console.log("Request received from "+ req.url); //打印请求的路径 res.writeHead(200, {'Content-Type': 'text/html'}); //设置响应头部,200表示一切正常 var html = fs.readFileSync(__dirname + '/index.html', 'utf-8'); //读取html文件,__dirname表示当前文件所在的目录路径 res.end(html); //将读取的内容返回 }); server.listen(3000); //监听3000端口 console.log("Server running at http://localhost:3000/");
Explain the code:
Create an index.html file under the nodejs-server folder for the HTML page returned to the client.
Enter the following code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Node.js Server</title> </head> <body> <h1>Node.js Server</h1> <p>Welcome to my Node.js Server!</p> </body> </html>
3. Run the project
Execute the following command on the console:
node server.js
Then enter http:/ in the browser /localhost:3000/, you can see a simple HTML page.
4. Summary
This article briefly introduces how to use Node.js to build a simple server and achieve basic HTML page access. Therefore, it can be understood that Node.js has good scalability and can easily implement basic operations such as data processing, observation and service environment control in web applications, jointly providing support for the creation of efficient web application platforms, and it can also be used as A more convenient choice for front-end developers.
The above is the detailed content of How to use Node.js to build a server and implement HTML5 pages. For more information, please follow other related articles on the PHP Chinese website!