Node.js编写一个文件服务器

'use strict';
var
    fs = require('fs'),
    url = require('url'),
    path = require('path'),
    http = require('http');

// 从命令行参数获取root目录,默认是当前目录:
var root = path.resolve(process.argv[2] || '.');

console.log('当前目录: ' + root);

// 创建服务器:
var server = http.createServer(function (request, response) {
    // 获得URL的path:
    var pathname = url.parse(request.url).pathname;
    // 获得对应的本地文件路径:
    var filepath = path.join(root, pathname);
    //设置默认文件:
    var defaultfile = ["index.html","default.html"];
    // 获取文件状态:
    fs.stat(filepath, function (err, stats) {
        if (err){
            // 出错了或者文件不存在:
            console.log('404 ' + request.url);
            // 发送404响应:
            response.writeHead(404);
            response.end('404 Not Found');
        } else if (stats.isFile()) {
            // 没有出错并且文件存在:
            console.log('200 ' + request.url);
            // 发送200响应:
            response.writeHead(200);
            // 将文件流导向response:
            fs.createReadStream(filepath).pipe(response);
        }else{
            //没有出错并且是目录
            console.log("200"+request.url);
            //发送200响应:
            response.writeHead(200);
            filepath = path.join(filepath,defaultfile.shift(1));
            fs.createReadStream(filepath).pipe(response);
        }
    });
});

server.listen(3000);

console.log('Server is running at http://127.0.0.1:3000/');

猜你喜欢

转载自blog.csdn.net/aganliang/article/details/88562046
今日推荐