简体   繁体   English

Node.js&Express:分部分提供文本文件

[英]Node.js & Express: Serving text files in parts

I have a webserver with node.js and express. 我有一个带有node.js的网络服务器并表达。 When I serve a text file that is big, it takes a lot of time to load into the browser. 当我提供一个很大的文本文件时,需要花费很多时间才能加载到浏览器中。 Imagine a 34 MB text file being served to the client, he would have to download the 34 MB only to check for something in the log file. 假设有一个34 MB的文本文件提供给客户端,他只需要下载34 MB即可检查日志文件中的内容。

Is there something I could do about it? 有什么我可以做的吗? Serve it in parts perhaps? 可以部分享用吗? Like: Part 1/10 - Part 10/10 喜欢:第1/10部分-10/10部分

To serve a file partial, you could take a byte range, and read that range with the filesystem function fs.createReadStream() . 要提供部分文件,您可以采用一个字节范围,并使用文件系统函数fs.createReadStream()读取该范围。 For example, if you wanted one tenth of a file, you could measure its size, and calculate the byte range. 例如,如果您想要文件的十分之一,则可以测量其大小并计算字节范围。

app.get('/log', function(req, res) {
  fs.stat('log.txt', function(err, stats) {
    var end = Math.ceil(stats.size / 10);
    var stream = fs.createReadStream('log.txt', {start: 0, end: end});

    var log = new String();
    readable.on('data', function(chunk) {
      log += chunk;
    });

    readable.on('end', function() {
      res.send(log);
    });
  });
});

You could always modify the code to send from 10-20%, or to send the last 10% of the file, etc. 您始终可以修改代码以发送10-20%的代码,或发送文件的最后10%的代码,依此类推。

Have you looked into Node streams ? 您是否研究过Node流 You can use them to send your data in small chunks, and offer feedback to show how much of it has been downloaded. 您可以使用它们以小块形式发送数据,并提供反馈以显示已下载了多少数据。

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

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