2013-07-10 54 views
0

我想讀一個文件,並回報以GET要求節點:如何讀取文件?

響應這是我在做什麼

app.get('/', function (request, response) { 
    fs.readFileSync('./index.html', 'utf8', function (err, data) { 
     if (err) { 
      return 'some issue on reading file'; 
     } 
     var buffer = new Buffer(data, 'utf8'); 
     console.log(buffer.toString()); 
     response.send(buffer.toString()); 
    }); 
}); 

index.html

hello world! 

當我加載localhost:5000頁面時,頁面旋轉,什麼也沒有發生,我在做什麼不正確這裏

我是newb即到節點。

+0

您的其他應用程序/服務器配置是什麼樣的?你看到任何控制檯輸出? – ZimSystem

回答

3

您正在使用同步版本的readFile method。如果這就是你的意圖,不要傳遞迴調。它返回一個字符串(如果你傳遞一個編碼):

app.get('/', function (request, response) { 
    response.send(fs.readFileSync('./index.html', 'utf8')); 
}); 

或者(和一般更恰當),可以使用異步方法(和擺脫編碼的,因爲你似乎是期待Buffer):

app.get('/', function (request, response) { 
    fs.readFile('./index.html', { encoding: 'utf8' }, function (err, data) { 
     // In here, `data` is a string containing the contents of the file 
    }); 
});