2017-07-01 32 views
-1

我試圖使用本地node.js服務器訪問我的計算機上的任意html文件。問題是,每當我嘗試使用「fs」模塊訪問文件時,「數據」變量即將出現未定義。使用本地Node.js測試服務器訪問文件

var http = require('http'); 
var fs= require('fs'); 
http.createServer(function (req, res) { 
    console.log(process.cwd()); 
    //because the response is in the callback of readfile it will only serve data after fs.readfile loads 
    fs.readFile('Desktop\Practice_page\HTML\PRAC.html',function(err, data){ 
    res.writeHead(200,{'Content-Type':'text/html'}); 
     if(data===undefined) 
      res.write("frick"); 
      else 
      res.write(data); 
     res.end(); 
    }); 
}).listen(8080); 

我的工作目錄是C:\用戶\ MYC,所以相對路徑應該是用戶\ MYC \桌面\等。我的語法有問題,還是我使用文件系統模塊錯了?

+0

您是否檢查過「err」包含的內容?你有完整的路徑嘗試? – JJJ

+0

是的,我使用\字符的絕對路徑加倍,它的工作。對不起,這個愚蠢的問題:/ –

回答

0

路徑錯誤。您必須使用__dirname來傳遞絕對路徑。

fs.readFile(__dirname + '\Practice_page\HTML\PRAC.html') 
0

您必須使用絕對路徑。請使用路徑模塊或添加完整的目錄列表。

相關問題