[英]Node: How to read file?
我想讀取文件並返回作為對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
,頁面旋轉並且什么也沒有發生,這是我在做什么錯
我是Node的新手。
您正在使用readFile
方法的同步版本。 如果這正是您的意圖,請不要將其傳遞給回調函數。 它返回一個字符串(如果您通過編碼):
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
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.