簡體   English   中英

NodeJS:使用 res.write() 加載 html

[英]NodeJS: load html with res.write()

我是 Node 的新手,所以我正在努力學習它。 我正在嘗試在 Node 中加載一個簡單的 HTML 文件,但這給了我一個錯誤,因為當我使用res.write(html)時未定義 HTML 我看到了一些與我相似的示例,所以我想了解什么是錯的這里。 我寫了這個:

const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    }
});

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    res.write(html);    
    res.end();
});

server.listen(port, hostname, () => {
    console.log('Server started on port ' + port);
});

您的問題是html變量未在您嘗試使用它的范圍內設置。

javascript 中的幾乎所有內容都是異步的,您需要處理和構建邏輯,以便從異步調用返回的值可以在程序的其他地方使用。

在你的情況下, readFile是一個異步調用,它讀取並返回文件——不幸的是,你接收 html 的回調有它自己的范圍,並且在你完成回調的執行后不可用。

有關如何執行此操作的規范強制性閱讀可在此處找到: 如何從異步調用返回響應?

這個問題有很多好的解決方案,例如使用閉包或承諾結構以及其他解決方案。

一個直接的解決方案是結合使用回調結構——就像在你的例子中那樣,讓html變量的用戶發生在readFile的回調范圍內,比如

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    fs.readFile('./index.html', (err, html) => {
        if(err)
           res.write("Error");    
        else
           res.write(html);    
        res.end();
    });
});

正如 Soren 指出的那樣,調用res.write()時未定義html 異步可以很方便,但是對於初學者來說有點難以理解。 最適合您的是嘗試處理異步任務的概念。 在那之前,您的問題的解決方案是使用fs.readFileSync同步版本, fs.readFile此處為文檔),並在createServer函數中調用它。

由於readFileSync同步返回讀取的內容,您可以這樣做:

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-type', 'text/html');
    var html = fs.readFileSync('./index.html');
    res.write(html);    
    res.end();
});

另一種選擇,正如我猜你試圖做的那樣,是在readFile的回調中初始化html變量。

var html_g; //global html variable
fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    } else {
        html_g = html; //html_g = content_of_index_file;
});

但是由於這個函數是異步的, createServer函數可以在html_g初始化之前被調用,從而導致問題。

const http = require('http');
const fs = require('fs');

const hostname = '127.0.0.1';
const port = 3000;

fs.readFile('./index.html', (err, html) => {
    if(err){
        throw err;
    } else if(html){
    const server = http.createServer((req, res) => {
       res.statusCode = 200;
       res.setHeader('Content-type', 'text/html');
       res.write(html);    
       res.end();
    });
}
});


server.listen(port, hostname, () => {
    console.log('Server started on port ' + port);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM