簡體   English   中英

為什么我的NodeJS Web服務器不能從目錄中獲取文件?

[英]Why isn't my NodeJS Web Server Fetching Files from my Directory?

我創建了一個BasicWebServer.js文件,該文件位於文件夾BasicWebServer.js portfolio-website ,該文件夾包含以下文件: index.htmBasicWebServer.jscss/style.css

我放入BasicWebServer.js文件中的代碼如下:

var http = require('http'),
    fs = require('fs'),
    path = require('path'),
    host = '127.0.0.1',
    port = '9000';

var mimes = {
    ".htm" : "text/html",
    ".css" : "text/css",
    ".js" : "text/javascript",
    ".gif" : "image/gif",
    ".jpg" : "image/jpeg",
    ".png" : "image/png"
}

var server = http.createServer(function(req, res){
    var filepath = (req.url === '/') ? ('./index.htm') : ('.' + req.url);
    var contentType = mimes[path.extname(filepath)];
    // Check to see if the file exists
    fs.exists(filepath, function(file_exists){
        if(file_exists){
            // Read and Serve
            fs.readFile(filepath, function(error, content){
                if(error){
                    res.writeHead(500);
                    res.end();
                } else{
                    res.writeHead(200, { 'Content-Type' : contentType});
                    res.end(content, 'utf-8');
                }
            })
        } else {
            res.writeHead(404);
            res.end("Sorry we could not find the file you requested!");
        }
    })
    res.writeHead(200, {'content-type' : 'text/html'});
    res.end('<h1>Hello World!</h1>');
}).listen(port, host, function(){
    console.log('Server Running on http://' + host + ':' + port);
});

更新1第1部分)

我刪除了兩行:

res.writeHead(200, {'content-type' : 'text/html'});
res.end('<h1>Hello World!</h1>');

當我刷新頁面時,我得到:

Sorry we could not find the file you requested!

第2部分)我還嘗試通過以下方法進行管道輸送:

var http = require('http'),
    fs = require('fs'),
    path = require('path'),
    host = '127.0.0.1',
    port = '9000';

var mimes = {
    ".htm" : "text/html",
    ".css" : "text/css",
    ".js" : "text/javascript",
    ".gif" : "image/gif",
    ".jpg" : "image/jpeg",
    ".png" : "image/png"
}

var server = http.createServer(function (req, res) {
    var filepath = (req.url === '/') ? ('./index.htm') : ('.' + req.url);
    var contentType = mimes[path.extname(filepath)];
    // Check to see if the file exists
    fs.exists(filepath, function(file_exists){
//        if(file_exists){
//            // Read and Serve
//            fs.readFile(filepath, function(error, content){
//                if(error){
//                    res.writeHead(500);
//                    res.end();
//                } else{
//                    res.writeHead(200, { 'Content-Type' : contentType});
//                    res.end(content, 'utf-8');
//                }
//            })
            res.writeHead(200, {'Content-Type' : contentType});
            var streamFile = fs.createReadStream(filepath).pipe(res);

            streamFile.on('error', function() {
                res.writeHead(500);
                res.end();
            })
        } else {
            res.writeHead(404);
            res.end("Sorry we could not find the file you requested!");
        }
    })
}).listen(port, host, function(){
    console.log('Server Running on http://' + host + ':' + port);
});

這給出了以下錯誤:

SyntaxError: Unexpected token else
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

這兩行:

res.writeHead(200, {'content-type' : 'text/html'});
res.end('<h1>Hello World!</h1>');

每次都在執行,它們在代碼有機會讀取文件之前被執行。 請記住, fs.exists()fs.readFile()是異步的,因此它們的響應會在其余代碼執行后出現。

如果我刪除了這兩行,您的代碼確實開始工作,因此,基本上,您要在其他代碼才有機會實際讀取並發送文件之前完成對這兩行的響應。


僅供參考,以fs.exists()的使用方式使用它被認為是反模式。 如果找不到該文件,則可以僅使用fs.readFile()並適當地處理該錯誤。 除了沒有並發問題外,這還少了一個文件操作。

為了教育起見,這是示例的有效版本,未使用fs.existsfs.readFile 而是使用fs.createReadStream.pipe.on('error'

var http = require('http'),
    fs = require('fs'),
    path = require('path'),
    host = '127.0.0.1',
    port = '9000';

var mimes = {
    ".htm": "text/html",
    ".css": "text/css",
    ".js": "text/javascript",
    ".gif": "image/gif",
    ".jpg": "image/jpeg",
    ".png": "image/png"
}

var server = http.createServer(function(req, res) {
    var filepath = (req.url === '/') ? ('./index.htm') : ('.' + req.url);
    var contentType = mimes[path.extname(filepath)];

    var file = fs.createReadStream(filepath);
    res.writeHead(200, {
        'Content-Type': contentType
    });
    file.pipe(res);
    file.on('error', function(err) {
        if (err.code === 'ENOENT') {
            res.writeHead(404);
            res.end("Sorry we could not find the file you requested!");
        } else {
            res.writeHead(500);
            res.end();
        }
    });

}).listen(port, host, function() {
    console.log('Server Running on http://' + host + ':' + port);
    console.log('Serving files from ' + process.cwd());
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM