2011-12-04 9 views
1

這實在是很奇怪的問題。我剛剛在我的系統上安裝了Node.JS(Fedora)。內部腳本和樣式表始終指向索引文件(Node.JS)

我在在/ var/WWW /鏡像/三個文件

  • server.js
  • client.js
  • 的index.html

文件服務器。 js是我通過CLI調用的那個:node server.js

它基本上返回index.html

var 
    http = require('http'), 
    io = require('socket.io'), 
    fs = require('fs'); 

http.createServer(function(request, response) { 

    fs.readFile(__dirname + '/index.html', function(error, data) { 

     if (error) { 

      result.writeHead(500); 

      console.log('Error: Could not read index.html.'); 

     } 

     response.writeHead(200, {'Content-Type': 'text/html'}); 
     response.end(data); 

    }); 

}).listen(1337, '127.0.0.1'); 

console.log('Server is running.'); 

所有按預期工作,沒有任何錯誤引發任何地方。

的index.html我有簡單的HTML5結構(沒有不必要的,真的!),並<script />指向,已經提到,client.js

這行代碼看起來是這樣的(Ctrl + U鍵;從瀏覽器):

<script src="client.js"></script>

通過在client.js移動光標,我得到實際位置:http://127.0.0.1:1337/client.js

似乎是對的,對不對?

問題:

通過打開它打開想要的文件的鏈接,但內容是server.js應返回。

這不允許我包含任何內部腳本和樣式表!

我想,任何通過http://127.0.0.1:1337/(也http://127.0.0.1:1337/client.jshttp://127.0.0.1:1337/a/b/c等)變爲通過server.js處理 - 和server.js回報的index.html(見上文)。

我該如何解決?謝謝你的任何建議!

+0

這裏沒有什麼奇怪的。 'FS。readFile(__ dirname +'/index.html',...'在代碼中,它只是做你想做的事 - 爲任何請求提供index.html。 – 2011-12-04 18:39:11

回答

1

看看req.url告訴你用戶正在請求的url。從那裏,你必須有一些代碼決定是否服務index.html或client.js。

此外,由於我猜測index.html不會頻繁更改,因此您應該只讀一次,並將緩衝區存儲在變量中,而不是在每次請求時都讀取它。

有一些模塊可以使服務靜態文件更容易一些。檢查filed一個相當不錯的獨立靜態文件

+0

[This](http:// www。 thecodinghumanist.com/blog/archives/2011/5/6/serving-static-files-from-node-js)使您的答案更加清晰。謝謝! – daGrevis

+0

PS **警告**:閱讀該文章的評論(參見上文)! – daGrevis