I recently needed to complete a course design and was assigned by the project manager (team leader) to write interface functions. The following editor will share with you through this article how to build a small server using node. Friends who need it can refer to it
Use node to build a small server (actually, it analyzes the URL and outputs the file to the client)
I recently needed to complete a course design, and was assigned by the project manager (team leader) to write the interface, but I always felt that I only wanted to write the front-end There is something missing, so I want to write the backend myself and play with it.
During this period, I was a little confused about which language to use. I originally planned to learn PHP, but then I thought about it, wouldn’t it be nice to use nodejs? Not only did I understand the background development, but it was also equivalent to It consolidates the foundation of js and kills two birds with one stone, which is great.
In the process of learning node, I learned how to use node to implement a server. It feels like a good summary of the modules learned previously. Four basic modules fs stream http path
are used. The code is as follows: (Contains broken English comments please forgive me)
'use strict' var url = require('url'); var path = require('path'); var fs = require('fs'); var http = require('http'); //get the current path //var root = path.resolve('.');//以当前的目录为服务器的根目录 var root = path.resolve(process.argv[2] || '.');//以输入的参数作为服务器的根目录,如果没有输入参数就将当前目录作为服务器根目录 console.log('local root dir :' + root); //create server var server = http.createServer(function(request, response) { //get the path of URL var pathname = url.parse(request.url).pathname; //get the local path var filepath = path.join(root, pathname); //get the file stat and output the request file by callback function fs.stat(filepath, function(err, stat) { if(!err && stat.isFile()) { console.log('200' + request.url); response.writeHead(200); fs.createReadStream(filepath).pipe(response);//没有必要手动读取文件内容。由于response对象本身是一个Writable Stream,直接用pipe()方法就实现了自动读取文件内容并输出到HTTP响应。 } else { console.log('404' + request.url); response.writeHead(404); response.end('404 Not Found'); } }); }); server.listen(8080); console.log('Server is running at http://127.0.0.1:8080/');
For some of the functions’s explanation:
path.resolve() 路径寻航(这名字不错) path.resolve([from…], to)
There is an interesting explanation: it is equivalent to continuously calling the system’s cd command
eg:
path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile') //相当于: cd foo/bar cd /tmp/file/ cd .. cd a/../subfile1 path.join([path1],path[2]...) 路径合并
Concatenate all names using path.seq Get up, and then format it with normailze
eg:
path.join('///foo', 'bar', '//baz/asdf', 'quux', '..'); =>'/foo/bar/baz/asdf'
Now that normalize
is mentioned:
Format path path.normalize(p)
Format paths that do not meet the specifications to simplify the processing of various complex path judgments among developers
eg:
path.normalize('/foo/bar//baz/asdf/quux/..'); => '/foo/bar/baz/asdf'
http.response.end() ends the response and tells the client All messages have been sent. This function must be called once when all content to be returned has been sent. If this function is not called, the client will be in the waiting state forever.
Usage:response.end([data], [encoding])
Detailed explanation of examples of using JavaScript to convert Chinese characters to Pinyin
3.Share 15 commonly used js regular expressions
4.Detailed explanation of examples of implementing search toolbar through javascript
5.Detailed introduction to the usage of async and await in Javascript
The above is the detailed content of Use node.js to analyze url output files to the client. For more information, please follow other related articles on the PHP Chinese website!