.html文件流返回前端
时间: 2023-06-13 17:05:01 浏览: 61
你可以使用Node.js中的`fs`模块读取HTML文件,然后将文件内容作为响应返回给前端。以下是一个示例代码:
```javascript
const http = require('http');
const fs = require('fs');
http.createServer((req, res) => {
if (req.url === '/') {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500, {'Content-Type': 'text/html'});
res.end('<h1>Internal Server Error</h1>');
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
}
});
} else {
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>Page Not Found</h1>');
}
}).listen(3000, () => {
console.log('Server running at http://localhost:3000');
});
```
在该示例中,当用户访问根路径时,服务器会读取`index.html`文件并将其内容作为响应返回。如果读取文件时出现错误,则返回500错误。如果用户访问了其他路径,则返回404错误。