node.js 用流返回数据失败?


const http = require("http");
const url = require("url");
const fs = require("fs");
const path = require("path");;

var server = http.createServer((request, response) => {
    response.writeHead(200, { 'Content-Type': 'text/html' });
    var workDir = path.resolve(".");
    var filePath = path.join(workDir, 'pub', 'index.html');
    var rs = fs.createReadStream(filePath, "utf-8");
    rs.on("data", (chunk) => {
        console.log(chunk);
        response.writeHead(200);
        rs.pipe(response);
    });
    rs.on("end", () => {
        console.log("end");
    });
    rs.on("error", (error) => {
        console.log(error);
    });
});
server.listen(3000);

index.html里面是有数据,但是浏览器访问index.html没有返回数据。这是为什么啊?

rs.on("data", (chunk) => {
        console.log(chunk);
        response.writeHead(200);
        fs.createReadStream(filePath, "utf-8").pipe(response);
    });

就好了

阅读 1.7k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题