"Node. JS Basics" (v) using MIME modules to respond to requests for CSS, JS files

Source: Internet
Author: User
Tags readfile

1. Overview

In the previous article, we implemented the client's routing request, including the direct use of JS to return the content response and use the HTML file response, but the last display in the previous article is only a very ordinary HTML file, can not use CSS style and JS file, Today we implement different file responses by setting the MIME type of the response file.

The article first describes what the MIME type is, and then describes two methods for setting the MIME type, the first is to determine the file type by the suffix name, and thus to respond, and the second is to respond with a third-party MIME module.

The example is extended on the basis of the previous article.

Introduction to 2.mime Types

MIME (Multipurpose Internet Mail Extensions) multi-purpose Internet Mail extension type. Is the type of file that sets the extension of an application to be opened by an app, and when the extension file is accessed, the browser automatically opens with the specified application. Many are used to specify some client-customized file names, as well as some ways to open media files. (Baidu Encyclopedia)

Simply put, MIME is an Internet standard, and by setting it you can set how the file opens in the browser. (If you are interested, you can try to open the HTML file with the CSS open way, more helpful to understand)

3. Two set MIME type methods 1. Direct extraction of file suffix name set MIME type

The code is based on the previous code, only changes the response this function, as follows:

//function response, HTML, CSS, JS and other files to respond to the clientvarResponse = function(res,filepath){    //Read the file and respond to the client after the read is completedFs.readfile (FilePath, function(err,data){        if(ERR) {//If it fails, it returns an error file            if(FilePath! = error)//If the failure is not an error file, the error file is returnedResponse (Res,error); }Else{//Get suffix name            vari = Filepath.lastindexof ('. ');varsuffix = filepath.substr (i+1, filepath.length); Res.writehead ( $,{//Respond to client, send file contents back                ' Content-type ':"text/"+suffix});//Specify MIME type by suffix nameRes.end (data); }    });};

The code is very easy, just use JS string operation to extract the suffix name, and then set in Wriethead content-type for text/plus suffix name on the line,

Then we add a CSS style to the chunxiao.html, and the chunxiao.html code is as follows:

<! DOCTYPE html><html><head>    <meta charset="UTF-8">    <title>Chunxiao</title>    <linkhref="./stylesheets/index.css" rel="stylesheet"  Type="Text/css">  </head><body><nav>Chunxiao</nav><div id="value">    <p>Spring sleep does not feel Xiao</P>    <p>Smell the birds everywhere</P>    <p>The night comes the sound of rain</P>    <p>How much does the flower fall?</P></div></body></html>

The code for INDEX.CSS is as follows:

Body{  background-color:#222222;} nav {  color:#cc0000;     font-weight:bold;  font-size:2em; }#value{  color:#cc0000;  font-size:2.1em; }

Start the server, which is visible when you visit the Web page:

The first method is actually the basis of the MIME module implementation. As mentioned above, MIME is set file type, css,html file type collation is "text/", but video file 3gp is "video/", picture file jpeg is "image/", ... There are many more formats on the Internet, and we have to implement them one by one, which makes it a unified and convenient MIME module for reuse.

2. Use the MIME module to set the file type

To use the MIME module, we must first learn the NPM tool. NPM is a package management and distribution tool that has now become the unofficial standard for publishing node modules (packages). With NPM, we can quickly find the package to use for a particular service, download, install, and manage the packages that are already installed.

With node. JS installed, NPM is typically installed and can be used directly in CMD. Start using NPM to install the mine module.

First we will go into our project folder and then use NPM to install MIME, as shown below:

The line is my project folder, box is npm Install command, after successful installation, in the project folder will appear a Npm_install folder, there is a MIME folder, now the project file structure is as follows:

Then we use the MIME module, first we want to use a variable to get the MIME module, at the beginning of the Luyou.js file to get the MIME module:

//获取mime模块varrequire("mime");

Then use the MIME variable in the response function to get the MIME type of the file

//function response, HTML, CSS, JS and other files to respond to the clientvarResponse = function (Res,filepath) {//Read the file and respond to the client after the read is completedFs.readfile (Filepath,function (err,data) {if(ERR) {//If it fails, it returns an error file            if(FilePath! = error)//If the failure is not an error file, the error file is returnedResponse (Res,error); }Else{/** * Second method: Set MIME type by using MIME module */Res.writehead ( $,{//Respond to client, send file contents back                ' Content-type ': Mime.lookup (FilePath)});//Specify MIME type by suffix nameRes.end (data); }    });

Consistent with the foregoing.

"Node. JS Basics" (v) using MIME modules to respond to requests for CSS, JS files

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.