Creating an HTTP Server
Creating HTTP servers using Node.js requires the use of built-in HTTP modules
Create a web server
Node.js is JavaScript that runs in a server environment. The server here refers to the physical concept of a server, namely a host. Using Node.js to create an HTTP server refers to a software concept server, namely a Web server, similar to Nginx and Apache
const http = require('http');
const server = http.createServer((req, res) = > {
res.write('Hello\n');
res.end();
});
server.listen(9527.() = > {
console.log('Web Server started at port 9527');
});
Copy the code
The 10 lines above create the simplest HTTP server that listens for port 9527 and returns a string upon receipt of the requestHello\n
You can use your browser or curl to test the curl tool
CreateServer’s callback function is called when the request is received
req
Req represents the HTTP request. It is a readable stream and usually has several attributes
- Url: the address of the local request
- Method: HTTP request methods (GET, POST, DELETE, PUT, etc.)
- Headers: : HTTP header of the request
res
Res represents this HTTP response, which is a writable stream. The commonly used attribute methods include
- WriteHead (statusCode,[, StatusMessage[, headers]]) : writeHead(statusCode,[, StatusMessage[, headers]]) : sends the response header, including the statusCode, status information, and response header
- Write (chunk) : Writes a string or buffer to the response body
- End (chunk) : Sends a signal to the server, which can carry the last data sent, indicating that all response headers and bodies have been sent. Each response needs to be called once
- GetHeader (name) : Returns the header of the specified name
- GetHeaders () : Returns the object containing all the header information
- SetHeader (name, value) : Set the response header to merge with writeHead() and use writeHead() first if there is a conflict.
- StatusCode: Sets the response HTTP status
The Web server that returns the requested information
All the requests in the above example return the same result. It is possible to do some differential processing for request identification. The following example shows how to return basic information for each request
const http = require('http');
const server = http.createServer((req, res) = > {
const { url, method, headers } = req;
res.setHeader('content-type'.'text/html');
res.write(` request URL:${url}\n`);
res.write('Request method:${method}\n`);
res.write('request headers:The ${JSON.stringify(headers, null.' ')}`);
res.end('\n');
});
server.listen(9527.() = > {
console.log('Web Server started at port 9527');
});
Copy the code
Return file contents
While the above example is far from a real Web server, the following example shows a simple static resource server that returns file content
const http = require('http');
const path = require('path');
const fs = require('fs');
const mime = require('mime-types');
// Static resource root directory, can be set as any local permission directory, into the A.jpg test
const ROOT_DIRECTORY = '/public';
const server = http.createServer((req, res) = > {
const { url } = req;
const filePath = path.join(ROOT_DIRECTORY, url);
fs.readFile(filePath, (err, chunk) = > {
if (err) {
res.writeHead(404, {
'content-type': 'text/html'}); res.end('File does not exist! ');
} else {
res.writeHead(200, {
'content-type': mime.contentType(path.extname(url)), }); res.end(chunk); }}); }); server.listen(9527.() = > {
console.log('Web Server started at port 9527');
});
Copy the code
Demo uses the mime-types package to obtain the content-type of a file based on the file name. To run demo, you need to install mime-types TNPM i-S mime-types in the code directory
The HTTP status code
- 200 OK: Indicates that the request is processed normally
- 404 Not Found: The requested resource does Not exist on the server
Place the image in the test directorya.jpg
Using browser tests127.0.0.1:9527 / a. pg
Reading movie files
In theory, the same code can be used to read a movie file, but in practice, it will be found that the movie file is returned to the browser after it has been fully read into memory, which takes a long time to return the content, and the program cannot handle the movie file if it is too large. HTTP protocol supports sectionalized Transfer (transfer-encoding: Chunked), and since res are writable streams, you can simply use stream to return the content to the browser as it is read, rather than once
const http = require('http');
const path = require('path');
const fs = require('fs');
const mime = require('mime-types');
// Static resource root directory
const ROOT_DIRECTORY = '/Users/undefined/node-demo/public';
const server = http.createServer((req, res) = > {
const { url } = req;
const filePath = path.join(ROOT_DIRECTORY, url);
fs.access(filePath, fs.constants.R_OK, err= > {
if (err) {
res.writeHead(404, {
'content-type': 'text/html'}); res.end('File does not exist! ');
} else {
res.writeHead(200, {
'content-type': mime.contentType(path.extname(url)), }); fs.createReadStream(filePath).pipe(res); }}); }); server.listen(9527.() = > {
console.log('Web Server started at port 9527');
});
Copy the code
You can easily import files into HTTP Response Node.js using fs.createreadstream () and pipe() described in the stream section. By the way, it introduces some HTTP protocol related knowledge, which is worth reading
The minimalist Node. Js introductory tutorial: www.yuque.com/sunluyong/n…
In this paper, a better reading experience: www.yuque.com/sunluyong/n…