文件服務(wù)器
讓我們繼續(xù)擴(kuò)展一下上面的Web程序。我們可以設(shè)定一個(gè)目錄,然后讓W(xué)eb程序變成一個(gè)文件服務(wù)器。要實(shí)現(xiàn)這一點(diǎn),我們只需要解析request.url中的路徑,然后在本地找到對(duì)應(yīng)的文件,把文件內(nèi)容發(fā)送出去就可以了。
解析URL需要用到Node.js提供的url模塊,它使用起來(lái)非常簡(jiǎn)單,通過(guò)parse()將一個(gè)字符串解析為一個(gè)Url對(duì)象:
'use strict';
var url = require('url');
console.log(url.parse('http://user:pass@host.com:8080/path/to/file?query=string#hash'));
- 鍵值對(duì)
- 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:pass@host.com:8080/path/to/file?query=string#hash' }
- Url {
個(gè)人博客: www.liangtongzhuo.com