为什么我的NodeJS Web服务器从我的目录中获取文件?

时间:2015-09-01 01:10:26

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

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

2 个答案:

答案 0 :(得分:3)

这两行:

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

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

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

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

答案 1 :(得分:0)

为了教育,以下是您的示例的工作版本,它既不使用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());
});