【问题标题】:Why isn't my NodeJS Web Server Fetching Files from my Directory?为什么我的 NodeJS Web 服务器不能从我的目录中获取文件?
【发布时间】:2015-11-26 03:05:54
【问题描述】:

我创建了一个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

【问题讨论】:

  • FWIW(在其他现有解决方案中)您可以使用fs.createReadStream,然后使用pipe

标签: javascript node.js server-side serverside-javascript


【解决方案1】:

为了便于学习,这里是您的示例的工作版本,它既不使用 fs.exists 也不使用 fs.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());
});

【讨论】:

  • 嗨,丹,感谢您的意见。我尝试了代码,但出现以下错误:Sorry we could not find the file you requested! 我的文件夹中是否缺少某些内容? :S
  • 它显示 404 消息,因为您请求 http://127.0.0.1:9000/./index.htm 不存在。请求一个确实存在的路径。
  • link 我想我请求的是正确的路径?
  • 使用新代码并检查它是否从该目录提供文件。
  • 谢谢!它工作正常,虽然我不得不将我的 index.htm 和 css 文件夹移动到桌面,因为在运行你的代码后,终端返回:Server Running on http://127.0.0.1:9000 Serving files from /Users/mahtabalam/Desktop` 即使BasicWebServer.js 在内部/Users/mahtabalam/Desktop/ma.com-website ,我不得不将 index.htm 和 css 文件夹从ma.com-website 文件夹中转移出来,并将它们放在桌面中。如何使 index.htm 与BasicWebServer.js 位置相同?再次感谢您的所有帮助:)
【解决方案2】:

这两行:

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

每次都被执行,并且在您的代码有机会读取文件之前执行。请记住,fs.exists()fs.readFile() 是异步的,因此它们的响应会在您的其余代码执行之后进行。

如果我删除这两行,您的代码确实开始工作,所以基本上您在其他代码有机会实际读取文件并发送之前完成了这两行的响应。


仅供参考,以您使用它的方式使用fs.exists() 被认为是一种反模式。如果找不到文件,您可以只使用fs.readFile() 并适当地处理错误。除了没有并发问题,这也是少了一个文件操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2014-11-24
    • 2023-04-05
    • 2014-09-18
    • 2015-06-23
    • 2017-09-28
    • 1970-01-01
    相关资源
    最近更新 更多