Detailed description of static resource processing in Nodejs and detailed description of nodejs static Resources

Source: Internet
Author: User

Detailed description of static resource processing in Nodejs and detailed description of nodejs static Resources

Preface

When I started to use Nodejs to write simple web servers, I always felt something was missing.

It turns out that I always output Hello World on the page! Ah, It Works. No static resources related to CSS and JS references have been processed yet.

At first, I thought it would be very easy to handle these things. It turns out that this is not just the case. On the way, we also encountered some mistakes that people may often take for granted. So I decided to record the processing of static resources in Nodejs.

Focus on Problems

REPRODUCE THE PROBLEM

The directory structure is displayed first.

E:\CODE\NODEJS\LEARN\WEB\EXPRESS-STATIC│ server.js│├─html│   index.html│└─public  ├─css  │   index.css  │  ├─imgs  │   1.gif  │  └─js      index.js

The skeleton of such a web project is built. The following describes how to use the http module of nodejs to implement a web server. The target region displays index.html.

Index.html

Index.css

* {  padding: 0px;  margin: 0px;}h1 {  color: yellowgreen;}body {  background-color: #2C001E;}

Server. js

Var http = require ('http'); var fs = require ('fs'); function handle_request (req, res) {// client requests to the server, to put it bluntly, it is a request for the content of the relevant file. Res. writeHead (200, {'content-type': 'text/html'}); res. end (get_file_content (_ dirname + '\' + 'html '+' \ '+ 'index.html');} function get_file_content (filepath) {return fs. readFileSync (filepath);} var server = http. createServer (handle_request); server. listen (0, 8080 );

The Code uses a variable named _ dirname, whose value is the absolute path of the current running file. Through this, we can assemble the full path of the file we want to obtain.

Run the code to enable the server.

node server.js

Problems Found

Then we open the browser and we will find such a scene.

Page with no effect

Not only is the CSS style not displayed, but even the image is not correctly displayed.

Then, open the browser console and we will find that the client sends three requests to the server:

Client request content

  1. Localhost: HTML code page
  2. Index.css: Style File
  3. 1. gif: Image File

The reason why we failed to see the specific effect is that the server did not return the relevant content correctly. In this way, I suddenly realized it. So this Silver Bullet is

Correctly return relevant content for each different resource request.

Solve the problem

My ideas:

  1. Analyze the request address. Split the file name and suffix.
  2. Complete the full path of relevant files in the file system according to the suffix.
  3. Read the content according to the full path and return it to the client.

Server. js

Then we simply modified server. js. Of course, this is just a simple example. Do not write the production code like this.

Var http = require ('http'); var fs = require ('fs'); function handle_request (req, res) {// whatever the request, for the file request, the content should be read and issued for the suffix. Var suffix = req. url. substr (req. url. length-4, req. url. length); var realpath = _ dirname + '\' + 'public' + '\'; var filename = req. url. substr (req. url. length-9); if (suffix = '.css ') {res. writeHead (200, {'content-type': 'text/css '}); res. end (get_file_content (realpath + '\ css \' + filename);} else if (suffix = '.gif ') {res. writeHead (200, {'content-type': 'image/gif'}); res. end (get_file_content (realpath + '\ imgs \ 1.gif');} else {res. writeHead (200, {'content-type': 'text/html'}); res. end (get_file_content (_ dirname + '\' + 'html '+' \ '+ 'index.html');} function get_file_content (filepath) {return fs. readFileSync (filepath);} var server = http. createServer (handle_request); server. listen (0, 8080 );

Then restart the server.

node server.js

Access the browser again

Http: // localhost: 8080

As follows:

Because there is no screen recording, GIF images are not displayed, but static resources are sufficient.

Express

Another useful web framework, express, is more convenient for static resources. It is a high-level encapsulation.

Core

You can use the express object app. use (express. static (folder_path) method. You can specify the parameters of the method as the corresponding static resource folder path.

Server-express.js

/*** Use express to control static resources. */Let express = require ('express '); let fs = require ('fs'); let path = require ('path'); var app = express (); app. use (express. static (path. join (_ dirname ,'. /public '); app. all ('/', function (req, res) {console. log ("============================================ = "); console. log ("Request Path:" + req. url); var filename = req. url. split ('/') [req. url. split ('/'). length-1]; var suffix = req. url. split ('. ') [req. url. split ('. '). length-1]; console. log ("file name:", filename); if (req. url = '/') {res. writeHead (200, {'content-type': 'text/html'}); res. end (get_file_content (path. join (_ dirname, 'html', 'index.html ');} else if (suffix = 'css') {res. writeHead (200, {'content-type': 'text/css '}); res. end (get_file_content (path. join (_ dirname, 'public', 'css ', filename);} else if (suffix in ['gif', 'jpeg', 'jpg ', 'png ']) {res. writeHead (200, {'content-type': 'image/'+ suffix}); res. end (get_file_content (path. join (_ dirname, 'public', 'images', filename) ;}}); function get_file_content (filepath) {return fs. readFileSync (filepath);} app. listen (0, 8080 );

Index.html

Because static resource control is used just now, we can simplify the spelling of static resource paths on HTML pages. For example:

The original HTML page should be written as follows:


Now you only need to write this:


It seems to be missing/public, but in fact, express can help us save a lot of boring work.

Then open the browser to view the specific static resource content.

What is the degree of support for different image types?

Modify the HTML page as follows:

Open a browser to view the support for gif, png, and jpg images?

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.