为什么我的 NodeJS Web 服务器不从我的目录中获取文件? [英] Why isn't my NodeJS Web Server Fetching Files from my Directory?

查看:49
本文介绍了为什么我的 NodeJS Web 服务器不从我的目录中获取文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 BasicWebServer.js 文件,该文件位于 portfolio-website 文件夹中,该文件夹包含以下文件:index.htm, BasicWebServer.js, css/style.css.

I created a BasicWebServer.js file which lives in the folder portfolio-website and this folder has the following files: index.htm, BasicWebServer.js, css/style.css.

我放在BasicWebServer.js文件中的代码如下:

The code I put in the BasicWebServer.js file is as following:

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>');

当我刷新页面时,我得到:

and when I refresh the page, I get:

抱歉,我们找不到您请求的文件!

第 2 部分)我也试过这样做:

Part 2) I have also tried piping it by doing this:

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() 是异步的,因此它们的响应是在您的其余代码执行之后.

Are getting executed every time and they get executed before your code has a chance to read the file. Remember, that fs.exists() and fs.readFile() are async so their response comes after the rest of your code executes.

如果我删除这两行,你的代码就会开始工作,所以基本上你已经用这两行完成了响应,然后你的其他代码才有机会实际读取文件并发送它.

If I remove those two lines, your code does start to work so basically you were finishing the response with those two lines before your other code had a chance to actually read the file and send it.

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

FYI, it is considered a bit of an anti-pattern to use fs.exists() the way you are using it. You can just use fs.readFile() and handle the error appropriately if the file is not found. Besides not having concurrency issues, this is also one less file operation.

这篇关于为什么我的 NodeJS Web 服务器不从我的目录中获取文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆