Home>Article>Web Front-end> Node.js creates Web and TCP servers

Node.js creates Web and TCP servers

小云云
小云云 Original
2017-12-06 13:08:18 1524browse

In this article, we mainly introduce the methods and processing techniques of using Node.js to create web servers and TCP servers. We hope it can help everyone.

Functions of the Web server:

Accept HTTP requests (GET, POST, DELETE, PUT, PATCH)

Processing HTTP request (handle it yourself, or request other programs to handle it)

Response (return pages, files, various data, etc.)

Common Web server architecture:

Nginx, Apache: Responsible for accepting HTTP requests, determining who will handle the request, and returning the result of the request

php-fpm / php Module: Process the requests assigned to itself and return the processing results to the assignor

Common request types:

Request files: including static Files (web pages, pictures, front-end JavaScript files, css files...), and files processed by the program

Complete specific operations: such as logging in, obtaining specific data, etc.

Node.js Web server:

Does not depend on other specific web server software (such as Apache, Nginx, IIS...)

Node.js code handles the logic of requests

Node.js code is responsible for various "configurations" of the Web server

Use Express to create a Web Server

Simple Express Server

Static File Service

Routing

Middleware

Simple Express server:


var express = require('express'); var app = express(); app.get('', function(req, res){  res.end('hello\n');  });  app.listen(18001, function afterListen(){  console.log('express running on http://localhost:18001');  });


Static file scope:

Web pages, plain text, images, front-end JavaScript code, CSS style sheet files, media files, font files

Use Express to access static files


app.use(express.static('./public'));


Routing:

Assign different requests to the corresponding processing functions

Distinguish: path, request method

Three routing implementation methods:

path: relatively simple

Router: more suitable for multiple sub-routes under the same route

route: More suitable for API

Middleware

Connect: Node.js middleware framework

Layered processing

Each layer implements a function

Create TCP server

Use net module to create TCP server

Use telnet to connect to the TCP server

Use net to create a TCP client


Use node.js to build a simple Web server JS code part:


var http = require('http'); var url = require('url'); var path = require('path'); var fs = require('fs'); var dir, arg = process.argv[2] || ''; // 命令行第三个参数,用来接收目录,可为空,相对当前server.js文件的目录名称 // 比如使用命令 node server debug,意思就是debug文件夹与server.js文件同级 // 且你想以debug文件夹启动web服务 http.createServer(function (req, res) { var pathname = __dirname + url.parse(req.url).pathname; dir = dir ? dir : pathname; // 记住dir(目录) pathname = dir ? pathname.replace(dir, dir + arg + '/') : pathname; // 替换文件静态路径 if (path.extname(pathname) == "") { pathname += "/"; } if (pathname.charAt(pathname.length - 1) == "/") { pathname += "index.html"; // 入口文件,此处默认index.html } fs.exists(pathname, function (exists) { if (exists) { switch (path.extname(pathname)) { case ".html": res.writeHead(200, {"Content-Type": "text/html"}); break; case ".js": res.writeHead(200, {"Content-Type": "text/javascript"}); break; case ".css": res.writeHead(200, {"Content-Type": "text/css"}); break; case ".gif": res.writeHead(200, {"Content-Type": "image/gif"}); break; case ".jpg": res.writeHead(200, {"Content-Type": "image/jpeg"}); break; case ".png": res.writeHead(200, {"Content-Type": "image/png"}); break; default: res.writeHead(200, {"Content-Type": "application/octet-stream"}); } // res可以自己添加信息来简单交互 比如可以修改点header信息 或者修改返回的资源数据 fs.readFile(pathname, function (err, data) { res.end(data); }); } else { res.writeHead(404, {"Content-Type": "text/html"}); res.end("

404 Not Found

"); } }); }).listen(8085, "127.0.0.5"); // 服务器端口 console.log("server running at http://127.0.0.5:8085/");


The above content is the Node.js method for creating Web and TCP servers. Hope it helps everyone.

Related recommendations:

PHP and Node.js

##Node.js learning TCP/IP data communication

Node.JS related knowledge

The above is the detailed content of Node.js creates Web and TCP servers. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn