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