Discuss / JavaScript / 自己根据上面写的有点长,主要获取文件信息那个方法有点多

自己根据上面写的有点长,主要获取文件信息那个方法有点多

Topic source

'use strict'; var url=require('url'), fs=require('fs'), path=require('path'), http=require('http'); var root = path.resolve(process.argv[2] || '.');

console.log('Static root dir: ' + root);

// 创建服务器: var server = http.createServer(function (request, response) { // 获得URL的path,类似 '/css/bootstrap.css': var pathname = url.parse(request.url).pathname; // 获得对应的本地文件路径,类似 '/srv/www/css/bootstrap.css': var filepath = path.join(root, pathname); // 获取文件状态: fs.stat(filepath, function (err, stats) { if (!err && stats.isFile()) { // 没有出错并且文件存在: console.log('200 ' + request.url); // 发送200响应: response.writeHead(200); // 将文件流导向response: fs.createReadStream(filepath).pipe(response); }//是目录 else if(!err&&stats.isDirectory()){ //查找目录下index.html是否存在 var newfilepath=path.join(root,'index.html'); //获取文件状态; fs.stat(newfilepath,function(err1,stats1){ if(!err1&&stats1.isFile()){ // 没有出错并且文件存在: console.log('200 ' + request.url); // 发送200响应: response.writeHead(200); // 将文件流导向response: fs.createReadStream(newfilepath).pipe(response); } else{ var newfilepath2=path.join(root,'default.html'); //获取文件状态; fs.stat(newfilepath2,function(err2,stats2){ if(!err2&&stats.isFile()){ // 没有出错并且文件存在: console.log('200 ' + request.url); // 发送200响应: response.writeHead(200); // 将文件流导向response: fs.createReadStream(newfilepath2).pipe(response); }else{ // 出错了或者文件不存在: console.log('404 ' + request.url); // 发送404响应: response.writeHead(404); response.end('404 Not Found'); } }); } });

    }else {
        // 出错了或者文件不存在:
        console.log('404 ' + request.url);
        // 发送404响应:
        response.writeHead(404);
        response.end('404 Not Found');
    }
});

});

server.listen(8080);

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


  • 1

Reply