Usage of Node.js http module

Usage of Node.js http module

Preface

The purpose of Node.js development is to write Web server programs in JavaScript. Because JavaScript has actually dominated browser-side scripting, its advantage is that it has the largest number of front-end developers in the world. If you have already mastered JavaScript front-end development, and then learn how to apply JavaScript in back-end development, you can become a true full-stack developer.

HTTP

To understand how a web server program works, first, we need to have a basic understanding of the HTTP protocol. If you are not familiar with the HTTP protocol, take a look at the HTTP protocol introduction first.

HTTP Server

It is unrealistic to develop an HTTP server program, process TCP connections, and parse HTTP from scratch. These tasks have actually been completed by the http module that comes with Node.js. The application does not deal directly with the HTTP protocol, but operates the request and response objects provided by the http module.

The request object encapsulates the HTTP request. We can get all the information of the HTTP request by calling the properties and methods of the request object.

The response object encapsulates the HTTP response. By operating the methods of the response object, we can return the HTTP response to the browser.

It is very simple to implement an HTTP server program using Node.js. Let's implement a simplest web program, hello.js, which returns Hello world! for all requests:

'use strict';
var http = require('http'); // Import the http module // Create an http server and pass in the callback function. The callback function receives the request and response objects var server = http.createServer(function (request, response){
console.log(request.method + ': ' + request.url); // Get the method and url of the HTTP request:
response.writeHead(200, {'Content-Type': 'text/html'}); // Write HTTP response 200 to response and set Content-Type: text/html
response.end('<h1>Hello world!</h1>'); });// Write the HTML content of the HTTP response to response
server.listen(8080); // Let the server listen to port 8080 console.log('Server is running at http://127.0.0.1:8080/');

Running the program in the command prompt, you can see the following output:

$ node hello.js Server is running at http://127.0.0.1:8080/

Do not close the command prompt, open the browser and enter http://localhost:8080 to see the server response:

At the same time, in the command prompt window, you can see the request information printed by the program:

GET: /

GET: /favicon.ico

This is our first HTTP server program!

File Server

Let's continue to expand the above web program. We can set up a directory and turn the web program into a file server. To achieve this, we only need to parse the path in request.url, then find the corresponding file locally and send the file content.

Parsing URLs requires the url module provided by Node.js. It is very simple to use. It parses a string into a Url object through parse():

'use strict';
var url = require('url');

console.log(url.parse('http://user:[email protected]:8080/path/to/file?query=string#hash'));

The results are as follows:

Url { protocol: 'http:', slashes: true, auth: 'user:pass', host: 'host.com:8080', port: '8080', hostname: 'host.com', hash: '#hash', search: '?query=string', query: 'query=string', pathname: '/path/to/file', path: '/path/to/file?query=string', href: 'http://user:[email protected]:8080/path/to/file?query=string#hash' }

To process local file directories, you need to use the path module provided by Node.js, which can easily construct directories:

'use strict';
var path = require('path');
var workDir = path.resolve('.'); // Resolve the current directory ('/Users/michael')
var filePath = path.join(workDir, 'pub', 'index.html'); // Combine the complete file path: current directory + 'pub' + 'index.html' ('/Users/michael/pub/index.html')

Use the path module to correctly handle operating system-dependent file paths. On Windows, the returned path is similar to C:\Users\michael\static\index.html, so we don't need to worry about concatenating the paths.

Finally, we implement a file server file_server.js:

'use strict';
var fs = require('fs'),url = require('url'),path = require('path'),http = require('http');
var root = path.resolve(process.argv[2] || '.'); // Get the root directory from the command line parameters, the default is the current directory console.log('Static root dir: ' + root);
var server = http.createServer(function (request, response){// Create a server var pathname = url.parse(request.url).pathname;// Get the path of the URL, similar to '/css/bootstrap.css'
var filepath = path.join(root, pathname); // Get the corresponding local file path, similar to '/srv/www/css/bootstrap.css'
fs.stat(filepath, function (err, stats) {if (!err && stats.isFile()) {// Get file statusconsole.log('200 ' + request.url);// No error and file existsresponse.writeHead(200);// Send 200 response// Direct file stream to response:
fs.createReadStream(filepath).pipe(response);    

} else {
console.log('404 ' + request.url); // Error or file does not exist response.writeHead(404); response.end('404 Not Found'); } }); }); // Send 404 response server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

There is no need to read the file contents manually. Since the response object itself is a Writable Stream, the pipe() method can be used to automatically read the file content and output it to the HTTP response.

Run node file_server.js /path/to/dir in the command line, change /path/to/dir to a valid directory on your local computer, and then enter http://localhost:8080/index.html in the browser:

As long as the file index.html exists in the current directory, the server can send the file content to the browser. Observe the console output:

200 /index.html

200 /css/uikit.min.css

200 /js/jquery.min.js

200 /fonts/fontawesome-webfont.woff2

The first request is the browser requesting the index.html page, and subsequent requests are requests for other resources sent by the browser after parsing the HTML.

practise

When you enter http://localhost:8080/ in the browser, 404 will be returned because the program recognizes that the HTTP request is not for a file but a directory. Please modify file_server.js; if the requested path is a directory, it will automatically search for index.html and default.html in the directory in turn. If found, it will return the content of the HTML file.

Reference source code

http server code (including static website)

https://github.com/michaelliao/learn-javascript/tree/master/samples/node/http

The above is the detailed usage of the http module of Node.js. For more information about Node.js, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Node.js Getting Started with the URL Module
  • In-depth understanding of the node.js path module
  • A brief introduction to http module and url module in node.js
  • In-depth understanding of node.js http module
  • How much do you know about the node.js-path module
  • Node.js Basics: Path Module, URL Module, and Detailed Explanation of the Use of http Module

<<:  Detailed tutorial on installing ElasticSearch 6.x in docker

>>:  Detailed explanation of MySQL syntax, special symbols and regular expressions

Recommend

How to use node scaffolding to build a server to implement token verification

content Use scaffolding to quickly build a node p...

Tutorial on installing MySQL 5.7.9 using RPM package under CentOS 7

Recorded MySQL 5.7.9 installation tutorial, share...

Solve the MySQL 5.7.9 version sql_mode=only_full_group_by problem

MySQL 5.7.9 version sql_mode=only_full_group_by i...

JavaScript to achieve skin effect (change background)

This article shares the specific code of JavaScri...

The difference between Input's size and maxlength attributes

I recently used the input size and maxlength attri...

Teach you how to build a Hadoop 3.x pseudo cluster on Tencent Cloud

1. Environmental Preparation CentOS Linux release...

CSS to achieve glowing text and a little bit of JS special effects

Implementation ideas: Use text-shadow in CSS to a...

CSS performance optimization - detailed explanation of will-change usage

will-change tells the browser what changes will h...

WeChat Mini Program to Implement Electronic Signature

This article shares the specific code for impleme...

How to implement call, apply and bind in native js

1. Implement call step: Set the function as a pro...

Analyzing the node event loop and message queue

Table of contents What is async? Why do we need a...