[英]Issue with loading chunks into the client
我正在嘗試創建一個 readableStream ,我將通過它發送數據塊(在這種情況下為 html )。 問題是,即使我設法獲取一大塊數據, res.write()
方法什么也不做,如果我記錄它只會返回 false。 我想知道這是為什么?
import { createServer } from 'http'
import { createReadStream } from 'fs'
const server = createServer((req, res) => {
if (req.method === 'GET') {
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' })
let readStream = createReadStream('./src/public/index.html', { encoding: 'utf8' })
readStream.on('data', (chunk) => {
console.log(chunk)
// html code
res.write(chunk)
// does nothing
})
res.end()
}
}
})
const PORT = 3000 || 8080
server.listen(PORT, () => { console.log(server.address()) })
您應該添加 pipe function 而不是定期寫入響應
readStream.on('open', function () {
// This just pipes the read stream to the response object (which goes to the client)
readStream.pipe(res);
});
// This catches any errors that happen while creating the readable stream (usually invalid names)
readStream.on('error', function(err) {
res.status(500).end(err);
});
更多信息: https://nodejs.org/en/knowledge/advanced/streams/how-to-use-fs-create-read-stream/
我希望它對你有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.