繁体   English   中英

为什么浏览器在使用 createReadStream() Node.js 时一直在加载

[英]Why Does Browser Keep Loading When Using createReadStream() Node.js

Node.js 新手我知道createReadStream()函数在性能上比readFile()更好,因为createReadStream()在夹头中读取和写入数据,而readFile()首先读取整个内容。 因此,如果文件很大,则readFile()函数可能需要更长的时间才能进一步处理数据。 因此我选择使用createReadStream()函数创建服务器,如下所示。

    // Create a server with fs.createReadStream(), better performance and less memory usage.
    http.createServer( function (request, response) {
      // Parse the request containing file name
      var pathname = url.parse(request.url).pathname;

      // Create a readable stream.
      var readerStream = fs.createReadStream(pathname.substr(1));

      // Set the encoding to be UTF8.
      readerStream.setEncoding('UTF8');

      // Handle stream events --> data, end and error
      readerStream.on('data', function(chunk) {
        // Page found
        // HTTP Status: 200 : OK
        // Content Type: text/plain
        response.writeHead(200, {'Content-type': 'text/html'});

        // Write the content of the file to response body.
        response.write(chunk);

        console.log('Page is being streamed...');
      });

      readerStream.on('end', function() {
        console.log('Page is streamed and emitted successfully.');
      });

      readerStream.on('error', function(err) {
        // HTTP Status: 404 : NOT FOUND
        // Content Type: text/plain
        response.writeHead(404, {'Content-type': 'text/html'});

        console.log('Page streaming error: ' + err);
      });

      console.log('Code ends!');

    }).listen(8081);

    // Console will print the message
    console.log('Server running at http://127.0.0.1:8081/');

我的.html.txt文件包含三行短文本。 启动服务器后,我通过访问http://127.0.0.1:8081/index.html访问我的网页。 一切正常,并且index.html的内容在浏览器上显示出来。

但是在浏览器的选项卡上,加载器图标一直在转动,就像在加载大约 1 分钟一样。

Node.js 服务器正常吗? 图标是否一直在转动,但对服务器没有任何费用? 或者我错过了什么并且图标不应该一直转动?

看起来您没有结束您的回复。 浏览器可能认为请求未完成,因此继续“加载”。

如果您查看开发者控制台中的网络选项卡,您可能会看到请求尚未完成。

你应该发送response.end()

此方法向服务器发出信号,表明所有响应标头和正文都已发送; 该服务器应认为此消息已完成。 必须在每个响应上调用 response.end() 方法。

我相信你应该在写头后在readerStream.on('end'readerStream.on('error'回调中调用response.end() 。这将告诉浏览器请求已完成,它可以停止加载动作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM