1. HTTP服务器:要开发HTTP服务器程序,从头处理TCP连接,解析HTTP是不现实的。这些工作实际上已经由Node.js自带的http模块完成了。应用程序并不直接和HTTP协议打交道,而是操作http模块提供的request和response对象。

    request对象封装了HTTP请求,我们调用request对象的属性和方法就可以拿到所有HTTP请求的信息;
    response对象封装了HTTP响应,我们操作response对象的方法,就可以把HTTP响应返回给浏览器。

    1. 'use strict'
    2. const http = require('http');
    3. let server = http.createServer((request, response) => {
    4. console.log(request.method, request.url);
    5. // 将HTTP响应200写入response, 同时设置Content-Type: text/html:
    6. response.writeHead(200, {'Content-Type': 'text/html'});
    7. // 将HTTP响应的HTML内容写入response:
    8. response.end('<h1>Hello world!</h1>');
    9. })
    10. // 让服务器监听8080端口:
    11. server.listen(8080);
    12. console.log("Server is running at http://127.0.0.1:8080/");

    在命令提示符下运行该程序,可以看到以下输出:

    1. $ node hello.js
    2. Server is running at http://127.0.0.1:8080/

    不要关闭命令提示符,直接打开浏览器输入http://localhost:8080,即可看到服务器响应的内容:
    18. HTTP - 图1
    同时,在命令提示符窗口,可以看到程序打印的请求信息:

    1. GET: /
    2. GET: /favicon.ico
    1. 文件服务器

    让我们继续扩展一下上面的Web程序。我们可以设定一个目录,然后让Web程序变成一个文件服务器。要实现这一点,我们只需要解析request.url中的路径,然后在本地找到对应的文件,把文件内容发送出去就可以了。
    解析URL需要用到Node.js提供的url模块,它使用起来非常简单,通过parse()将一个字符串解析为一个Url对象:

    1. 'use strict'
    2. const url = require('url');
    3. // 通过url.parse来解析url,并返回一个对象
    4. console.log(url.parse('http://user:pass@host.com:8080/path/to/file?query=string#hash'));

    结果如下:

    1. Url {
    2. protocol: 'http:',
    3. slashes: true,
    4. auth: 'user:pass',
    5. host: 'host.com:8080',
    6. port: '8080',
    7. hostname: 'host.com',
    8. hash: '#hash',
    9. search: '?query=string',
    10. query: 'query=string',
    11. pathname: '/path/to/file',
    12. path: '/path/to/file?query=string',
    13. href: 'http://user:pass@host.com:8080/path/to/file?query=string#hash' }

    处理本地文件目录需要使用Node.js提供的path模块,它可以方便地构造目录:

    1. 'use strict'
    2. const path = require('path');
    3. // // 解析当前目录:
    4. let workPath = path.resolve('.');
    5. // // 组合完整的文件路径:当前目录+'pub'+'index.html':
    6. let pt = path.join(workPath,'pub','index.html');
    7. console.log(pt);
    8. // D:\研究生\学习\Nodejs\http\pub\index.html

    使用path模块可以正确处理操作系统相关的文件路径。在Windows系统下,返回的路径类似于C:\Users\michael\static\index.html,这样,我们就不关心怎么拼接路径了。
    最后,我们实现一个文件服务器file_server.js:

    1. 'use strict'
    2. const fs = require('fs'),
    3. http = require('http'),
    4. path = require('path'),
    5. url = require('url');
    6. let root = path.resolve(process.argv[2] || '.');
    7. console.log(root);
    8. let server = http.createServer((request, response) => {
    9. var pathname = url.parse(request.url).pathname;
    10. // 获得对应的本地文件路径,类似 '/srv/www/css/bootstrap.css':
    11. var filePath = path.join(root, pathname);
    12. fs.stat(filePath,(err,stats) => {
    13. if(!err && stats.isFile()) {
    14. console.log('200' + request.url);
    15. response.writeHead(200);
    16. fs.createWriteStream(filePath).pipe(response);
    17. }else {
    18. console.log('404' + request.url);
    19. response.writeHead(404);
    20. response.end('404 Not Found');
    21. }
    22. })
    23. })
    24. server.listen(8080);
    25. console.log('Server is running at http://127.0.0.1:8080/');

    没有必要手动读取文件内容。由于response对象本身是一个Writable Stream,直接用pipe()方法就实现了自动读取文件内容并输出到HTTP响应。
    在命令行运行node file_server.js /path/to/dir,把/path/to/dir改成你本地的一个有效的目录,然后在浏览器中输入http://localhost:8080/index.html: