代码之家  ›  专栏  ›  技术社区  ›  O Connor

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

  •  1
  • O Connor  · 技术社区  · 6 年前

    createReadStream() 功能比性能更好 readFile() ,因为 createReadStream() 读取和写入卡盘中的数据 读取文件() 读取文件() 函数可能需要更长的时间才能进一步处理数据。因此,我选择使用 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

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

    1 回复  |  直到 4 年前
        1
  •  2
  •   Andrew Lohr    6 年前

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

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

    response.end()

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

    我想你应该打电话来 response.end() 在两个 readerStream.on('end' readerStream.on('error' 在你写了头之后回叫。这将告诉浏览器请求已完成,并且可以停止加载操作。