In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about how to use Node.js to achieve a static resource server. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.
The project involves modules such as http, fs, url, path, zlib, process, child_process, etc., covering a large number of commonly used api;, including caching strategy selection based on http protocol, gzip compression optimization, etc.
You can experience the project effect first:
Installation: npm I-g here11
Enter any folder address command: here
Step1 New Project
Because we are going to publish to npm, so we first follow the international practice, npm init, go you! You can enter all the way from the command line, and some configurations will be described in more detail in the later release steps.
The directory structure is as follows:
The bin folder holds our execution code, and web acts as a test folder with some web pages in it.
Step2 code
Step2.1 embryonic form
The static resource server, generally speaking, means that we enter an address such as "http:// domain name / test/index.html" in the browser address bar. The server finds the index.html from the corresponding folder under the root directory, reads the contents of the file and returns it to the browser, and the browser renders it to the user.
Const http = require ("http"); const url = require ("url"); const fs = require ("fs"); const path = require ("path"); const item = (name, parentPath) = > {let path = parentPath = `${parentPath} / ${name} `.slice (1); return` ${name} `;} const list = (arr, parentPath) = > {return arr.map (name = > item (name, parentPath). Join (")) } const server = http.createServer ((req, res) = > {let _ path = url.parse (req.url). Pathname;// remove search let parentPath = _ path; _ path = path.join (_ _ dirname, _ path); try {/ / get the file description object let stats = fs.statSync (_ path) corresponding to the path If (stats.isFile ()) {/ / is a file, which returns the file content let file = fs.readFileSync (_ path); res.end (file);} else if (stats.isDirectory ()) {/ / is a directory and returns a directory list, so that users can continue to click let dirArray = fs.readdirSync (_ path) Res.end (list (dirArray, parentPath));} else {res.end ();}} catch (err) {res.writeHead (404, "Not Found"); res.end ();}}); const port = 2234; const hostname = "127.0.0.1" Server.listen (port, hostname, () = > {console.log (`server is running on http://${hostname}:${port}`);})
The above code is our core code, has achieved the core functions, local operation can see the return of the file directory, click on the file name to browse the corresponding web pages, pictures, text.
Step2.2 optimization
The function has been realized, but we can optimize it in some aspects, improve its practicality, and learn a few more api by the way.
1. Stream
At present, we read the file and return it to the browser through readFile, which of course can achieve the function, but we have a better way to use stream (stream) for IO operation. Stream is not a unique concept of node.js, but the most basic form of operation of the operating system, so in theory, any server language implements the API of stream.
Why is using stream a better way? Because reading and manipulating large files at one time, memory and network are unbearable, especially in the case of large user visits; and with the help of stream, you can make data flow and operate little by little, thus improving performance. The code is modified as follows:
If (stats.isFile ()) {/ / is a file, and the callback function passed in during createServer is added to the "request" event. The two formal parameters req and res / / of the callback function are http.IncomingMessage object and http.ServerResponse object / / respectively, and they both implement the stream interface let readStream = fs.createReadStream (_ path); readStream.pipe (res);}
The coding implementation is very simple, and when we need to return the contents of the file, we create a readable stream and direct it to the res object.
2. Gzip compression
The improvement in performance (user access experience) brought about by gzip compression is very obvious. Enabling gzip compression can greatly reduce the volume of file resources such as js and css, and improve the access speed of users. As a static resource server, we certainly need to add this function.
There is a zlib module in node that provides a lot of compression-related api, which we use to implement:
Const zlib = require ("zlib"); if (stats.isFile ()) {/ / is a file and returns the file content res.setHeader ("content-encoding", "gzip"); const gzip = zlib.createGzip (); let readStream = fs.createReadStream (_ path); readStream.pipe (gzip) .pipe (res);}
With the experience of using stream, it will be much easier for us to understand when we look at this code. Direct the file stream to the gzip object first, and then to the res object. In addition, there is one more thing to note when using gzip compression: you need to set the content-encoding in the response header to gzip. Otherwise, the browser will show a bunch of garbled codes.
3. Http cache
Caching is a thing that people love and hate, and when used well, it can enhance the user experience and reduce the pressure on the server; if you don't use it well, you may face all kinds of strange problems. Generally speaking, browser http cache is divided into strong cache (non-verification cache) and negotiation cache (verification cache).
What is strong caching? Strong caching is controlled by two header fields, cache-control and expires, and cache-control is now commonly used. For example, we set the response header of cache-control: max-age=31536000, which tells the browser that the resource has a cache period of one year, and the resource can be read directly from the cache without sending a request to the server within one year.
Negotiable cache uses the first fields such as if-modified-since/last-modified and if-none-match/etag, combined with strong cache, to send a request to the server when the strong cache misses (or tells the browser no-cache) to confirm the validity of the resource and decide to read or return the new resource from the cache.
With the above concepts, we can develop our caching strategy:
If (stats.isFile ()) {/ / is a file, return the file content / / add to determine whether the file has been changed, return the logic of 304without change / / get the modified time let IfModifiedSince = req.headers ["if-modified-since"] from the request header; / / get the modification date of the file-timestamp format let mtime = stats.mtime / / if the file modification time on the server is less than or equal to the modification time carried by the request header, it is determined that the file has not changed if (IfModifiedSince & & mtime {console.log (`server is running on http://${config.hostname}:${config.port}`);})
Here is a simple example of a chestnut, we can play freely!
5. Automatically open the browser
Although not too big eggs, but still need to add. I just want you to know that after I add it, you will be what you are:-(duang~
Const exec = require ("child_process") .exec; server.listen (config.port, config.hostname, () = > {console.log (`server is running on http://${config.hostname}:${config.port}`); exec (`open http://${config.hostname}:${config.port}`);}))
6. Process.cwd ()
Replace _ _ dirname with process.cwd ().
We finally want to make a global command that can be called in any directory, so the code for stitching path is modified as follows:
/ / _ _ dirname is the directory address of the current file, and process.cwd () returns the path where the script executes _ path = path.join (process.cwd (), _ path).
Step3 release
Basically, our code has been written, so we can consider releasing it!
Step3.1 package.json
You get a configuration similar to the json file shown below:
{"name": "here11", "version": "0.0.13", "private": false, "description": "a node static assets server", "bin": {"here": ". / bin/index.js"}, "repository": {"type": "git" "url": "https://github.com/gww666/here.git"}," scripts ": {" test ":" node bin/index.js "}," keywords ": [" node "]," author ":" gw666 "," license ":" ISC "}
Among them, bin and private are more important, and the rest are filled in according to their own projects.
Bin this configuration represents the file that we run the here command to execute after npm I-g xxx, and the name "here" can be chosen at will.
Step3.2 declares the script execution type
Add: #! / usr/bin/env node to the beginning of the index.js file
Otherwise, an error will be reported when running on linux.
Step3.3 registers a npm account
Reluctantly stick to the order, it is not clear to own Baidu:
If you don't have an account, add one first, and execute:
Npm adduser
Then fill in one by one
Username: your name
Password: your password
Email: yourmail
Npm will send you a verification email, remember to click, or the publication will fail.
Execute the login command:
Npm login
Execute the publish command:
Npm publish
After reading the above, do you have any further understanding of how to use Node.js to implement a static resource server? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.