2017-04-16 16 views
0

我有一個以/ opt/battleship下的server.js開頭的NodeJS項目。如果我cd到該目錄並鍵入節點服務器,一切正常,但如果我坐在/ root並使用絕對路徑啓動它,如node /opt/battleship/server,那麼我從它的./lib和./public子目錄中提供的所有內容得到一個404響應。這是生產中的問題,因爲我/etc/init/battleship.conf腳本指定啓動在啓動過程中與尋找更乾淨的方式將NodeJS作爲具有絕對路徑的服務運行

exec /usr/local/bin/node /opt/battleship/server.js >> /var/log/battleship.log 2>&1 

它運行,但後來我得到的404錯誤。如果我放線

cd /opt/battleship 

正上方,在battleship.conf文件,我不明白404的錯誤,我正確地得到我的所有文件,但它好像在.conf文件使用光盤凌亂且容易出錯。糾正我,如果我錯了,這是我的第一個手寫.conf文件。有沒有更好的方法讓我的server.js服務器正確地從它的./lib和./public子目錄中創建文件?下面是引用我server.js文件:

var PORT  = 3000; 

var requirejs = require('requirejs'); 
var http  = requirejs('http'); 
var fs  = requirejs('fs'); 
var path  = requirejs('path'); 
var mime  = requirejs('mime'); 
var cache  = {}; 

requirejs.config({ 
    baseUrl: __dirname, 
    nodeRequire: require, 
     packages: [ 
      {name: 'ship', location: 'public/js/lib/ship'}, 
      {name: 'GameState', location: 'public/js/lib', main: 'GameState'} 
    ] 
}); 

requirejs(['./lib/battleship_server'], function(battleship_server) { 
    function send404(response) { 
     response.writeHead(404, {'Content-Type': 'text/plain'}); 
     response.write('Error 404: response not found.'); 
     response.end(); 
    } 

    function sendFile(response, filePath, fileContents) { 
     response.writeHead(
      200, 
      {'Content-Type': mime.lookup(path.basename(filePath))} 
     ); 
     response.end(fileContents); 
    } 

    function serveStatic(response, cache, absPath) { 
     if (cache[absPath]) { 
      sendFile(response, absPath, cache[absPath]); 
     } else { 
      fs.exists(absPath, function(exists) { 
       if (exists) { 
        fs.readFile(absPath, function(err, data) { 
         if (err) { 
          send404(response); 
         } else { 
          cache[absPath] = data; 
          sendFile(response, absPath, data); 
         } 
        }); 
       } else { 
        send404(response); 
       } 
      }); 
     } 
    } 

    var server = http.createServer(function(request, response) { 
     var filePath = false; 

     if (request.url === '/') { 
      filePath = 'public/index.html'; 
     } else { 
      filePath = 'public' + request.url; 
     } 
     var absPath = './' + filePath; 
     serveStatic(response, cache, absPath); 
    }); 

    server.listen(PORT, function() { 
     console.log('Server listening on port ' + PORT + '.'); 
    }); 

    battleship_server(server); 
}); 

回答

1

使用__dirname拿到腳本的文件夾中。

例如,如果你想獲得index.html,並且它在腳本的目錄,使用:

var path = require('path'); 

var pathOfIndex = path.join(__dirname, "index.html"); 
+1

問題解決了!非常感謝!從/etc/init/battleship.conf文件卸下'坎德拉/選擇/ battleship',並且從改變線在server.js: '變種ABSPATH = './' +文件路徑;' 到 'var absPath = path.join(__ dirname,filePath);' 完美工作。 –

相關問題